@humain/humain-code 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (650) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +2 -2
  3. package/dist/bundle/agent-monitor.js +1 -1
  4. package/dist/bundle/chunks/anthropic-messages-UZB5HJE3.js +77 -0
  5. package/dist/bundle/chunks/anthropic.js +25 -24
  6. package/dist/bundle/chunks/azure-openai-responses-J3LCMWPQ.js +15 -0
  7. package/dist/bundle/chunks/bedrock-converse-stream.js +460 -431
  8. package/dist/bundle/chunks/bowser-DXKSTXFQ.js +89 -0
  9. package/dist/bundle/chunks/{chunk-HTA325LJ.js → chunk-2NVGOSBN.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-5B25YXF7.js → chunk-3CGMVKHA.js} +13 -3
  11. package/dist/bundle/chunks/{chunk-SCINMV4X.js → chunk-46C6D7UC.js} +22 -21
  12. package/dist/bundle/chunks/{chunk-RS6PZK35.js → chunk-4EV7CK26.js} +249 -216
  13. package/dist/bundle/chunks/{chunk-T7BXP46S.js → chunk-4SFWYKL5.js} +1848 -1662
  14. package/dist/bundle/chunks/{chunk-TGDPZCSW.js → chunk-4TDNOR36.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-C6VERWRZ.js → chunk-4XF5JX7X.js} +1 -1
  16. package/dist/bundle/chunks/chunk-6HTHDVJC.js +4 -0
  17. package/dist/bundle/chunks/{chunk-2G7YVAVF.js → chunk-7EONJCBE.js} +1 -1
  18. package/dist/bundle/chunks/chunk-7H2WNBX7.js +11 -0
  19. package/dist/bundle/chunks/{chunk-2FYYW6FY.js → chunk-7OZNMWAJ.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-R6YQR7TZ.js → chunk-7WE77IE3.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-Z5YLKK3S.js → chunk-7WETECIB.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-EIC7CQX3.js → chunk-AI7EHDAX.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-KRCX3ZBA.js → chunk-APNPBT7Y.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-4HTVBBJD.js → chunk-ATFZAFMS.js} +2 -2
  25. package/dist/bundle/chunks/{chunk-R5OOX7RW.js → chunk-B47PNNLL.js} +9 -2
  26. package/dist/bundle/chunks/{chunk-AZXVJN6E.js → chunk-C4DHVDYT.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-4PRNKB6V.js → chunk-CET2MXXN.js} +7 -7
  28. package/dist/bundle/chunks/{chunk-66FZJO75.js → chunk-CU6KU7JK.js} +472 -3924
  29. package/dist/bundle/chunks/{chunk-MD7K7RPN.js → chunk-D3KYOSQY.js} +1 -1
  30. package/dist/bundle/chunks/{chunk-I3NDOUHE.js → chunk-DCXHRP6C.js} +1 -1
  31. package/dist/bundle/chunks/{chunk-OB332KMV.js → chunk-DD5UT56Y.js} +46 -32
  32. package/dist/bundle/chunks/{chunk-G4QPSFBF.js → chunk-EMBIUIQ2.js} +216 -223
  33. package/dist/bundle/chunks/{chunk-Q7VXYXY3.js → chunk-ENBDASDN.js} +2 -2
  34. package/dist/bundle/chunks/{chunk-2H3LUS62.js → chunk-FJIISX5W.js} +241 -229
  35. package/dist/bundle/chunks/{chunk-WQOOJP7U.js → chunk-GV5OVRKK.js} +1 -1
  36. package/dist/bundle/chunks/{chunk-KTSJYIYC.js → chunk-HHWVVNGG.js} +1 -1
  37. package/dist/bundle/chunks/{chunk-4JRER4XK.js → chunk-HQMUDHC3.js} +19 -19
  38. package/dist/bundle/chunks/{chunk-WQ7EJQIT.js → chunk-IOLLZXQN.js} +225 -239
  39. package/dist/bundle/chunks/chunk-IXQYPQRQ.js +2079 -0
  40. package/dist/bundle/chunks/{chunk-RU7ADKA7.js → chunk-J4GII2EE.js} +112 -96
  41. package/dist/bundle/chunks/chunk-J5TSAJGC.js +22 -0
  42. package/dist/bundle/chunks/{chunk-QT6ZHDMP.js → chunk-JBSWWCT5.js} +1 -1
  43. package/dist/bundle/chunks/{chunk-P6AXBESH.js → chunk-JV7VHOAY.js} +1119 -1098
  44. package/dist/bundle/chunks/{chunk-PWUDFU5V.js → chunk-JWOPWHVH.js} +4 -4
  45. package/dist/bundle/chunks/{chunk-4V5VL2BO.js → chunk-KLSRGGOH.js} +131 -154
  46. package/dist/bundle/chunks/{chunk-JF7FYXAI.js → chunk-KONLZKPL.js} +7 -6
  47. package/dist/bundle/chunks/{chunk-32QLLD2P.js → chunk-KQXXBQ57.js} +360 -332
  48. package/dist/bundle/chunks/{chunk-UZNIPOGS.js → chunk-L4J7SMJB.js} +1 -1
  49. package/dist/bundle/chunks/chunk-MPRAQ6ZI.js +41 -0
  50. package/dist/bundle/chunks/{chunk-GUHNFZ2Q.js → chunk-NNWNIBLG.js} +20 -19
  51. package/dist/bundle/chunks/{chunk-TWAHPPXN.js → chunk-OVDMYBIT.js} +1307 -1194
  52. package/dist/bundle/chunks/{chunk-WAPZN4KP.js → chunk-P2Y2H7SD.js} +2 -2
  53. package/dist/bundle/chunks/{chunk-PPBDDQHP.js → chunk-PGVDL4KB.js} +7 -6
  54. package/dist/bundle/chunks/{chunk-XHDVDJM7.js → chunk-PVNXN2TC.js} +7 -7
  55. package/dist/bundle/chunks/{chunk-RNBZBCH2.js → chunk-QJB5YI3I.js} +1 -1
  56. package/dist/bundle/chunks/{chunk-I5E7RQ5V.js → chunk-QRYDGY5I.js} +5 -5
  57. package/dist/bundle/chunks/{chunk-4QAXV5T6.js → chunk-R3VDXQW2.js} +9 -9
  58. package/dist/bundle/chunks/chunk-SKCJ25SX.js +24 -0
  59. package/dist/bundle/chunks/chunk-SQ7NTRLJ.js +77 -0
  60. package/dist/bundle/chunks/{chunk-SSRCVJZK.js → chunk-TYN46EVI.js} +5 -5
  61. package/dist/bundle/chunks/{chunk-6E6RHNOU.js → chunk-UXM4WFLH.js} +12 -11
  62. package/dist/bundle/chunks/{chunk-LB4CIS4F.js → chunk-VCMXBP5S.js} +17 -17
  63. package/dist/bundle/chunks/{chunk-N2SNMUD3.js → chunk-VKQNYZUA.js} +1 -1
  64. package/dist/bundle/chunks/{chunk-JYWUOKOI.js → chunk-WBSGWISD.js} +367 -353
  65. package/dist/bundle/chunks/{chunk-3EDMWQ35.js → chunk-WGXMYMPE.js} +17 -15
  66. package/dist/bundle/chunks/chunk-WRYGY5XG.js +24 -0
  67. package/dist/bundle/chunks/{chunk-GRJUKEE3.js → chunk-XVIQYONJ.js} +4 -4
  68. package/dist/bundle/chunks/chunk-YSWDFV2L.js +11 -0
  69. package/dist/bundle/chunks/{chunk-AEWYICBL.js → chunk-Z5UFSRO4.js} +2 -2
  70. package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
  71. package/dist/bundle/chunks/chunk-ZTG5OKI7.js +3 -0
  72. package/dist/bundle/chunks/{cli-H4LJNE2V.js → cli-6DJO467D.js} +2 -2
  73. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-T5R2RVFQ.js → cloudflare-workers-ai-system-one-ETKC6B2S.js} +1 -1
  74. package/dist/bundle/chunks/codemode-worker.js +68 -68
  75. package/dist/bundle/chunks/compat-HS4ARZK3.js +15 -0
  76. package/dist/bundle/chunks/curator-server-TC7RVVN2.js +3600 -0
  77. package/dist/bundle/chunks/dist-35STTNYA.js +37 -0
  78. package/dist/bundle/chunks/{dist-FMWWM4H7.js → dist-5AQPJ2TI.js} +2 -2
  79. package/dist/bundle/chunks/{dist-NHQTBDHT.js → dist-DYB3AR7C.js} +91 -257
  80. package/dist/bundle/chunks/dist-NMEXYUP3.js +11 -0
  81. package/dist/bundle/chunks/dist-cjs-EROMDUKS.js +193 -0
  82. package/dist/bundle/chunks/{easter-egg-3d-BUEOC3NO.js → easter-egg-3d-VVUF3C3X.js} +1 -1
  83. package/dist/bundle/chunks/entry-2GZ3PTWQ.js +2 -0
  84. package/dist/bundle/chunks/{entry-A2CSLKHC.js → entry-SRYLSS5P.js} +3 -3
  85. package/dist/bundle/chunks/{event-streams-7YGFEPBZ.js → event-streams-F67JLS6B.js} +1 -1
  86. package/dist/bundle/chunks/{execute-MY5JSEPV.js → execute-I3WGGPWL.js} +2 -2
  87. package/dist/bundle/chunks/{extract-PTGACPGP.js → extract-QHZTEVJP.js} +68 -65
  88. package/dist/bundle/chunks/{flow-implementer-APJFY4YI.js → flow-implementer-QMN3HKE2.js} +8 -9
  89. package/dist/bundle/chunks/github-copilot.js +55 -45
  90. package/dist/bundle/chunks/google-generative-ai-ZND73WDQ.js +22 -0
  91. package/dist/bundle/chunks/google-vertex-YAH62YRM.js +25 -0
  92. package/dist/bundle/chunks/host-Q565BCXB.js +3 -0
  93. package/dist/bundle/chunks/image-resize-worker.js +3 -3
  94. package/dist/bundle/chunks/{index.bundle-THL4EUSU.js → index.bundle-HONF3PUD.js} +177 -176
  95. package/dist/bundle/chunks/{inprocess-5NP5VJHZ.js → inprocess-453SLFL5.js} +6 -6
  96. package/dist/bundle/chunks/interactive-mode-MVZOJ5OU.js +5 -0
  97. package/dist/bundle/chunks/{llama-cpp-classify-GJAXULWL.js → llama-cpp-classify-Z4GZY4GC.js} +1 -1
  98. package/dist/bundle/chunks/mistral-conversations-7I5JURDP.js +43 -0
  99. package/dist/bundle/chunks/{node-ZFIIS5IM.js → node-IMSYVRPL.js} +53 -30
  100. package/dist/bundle/chunks/{node-UNHECG4X.js → node-MHHE76P4.js} +475 -440
  101. package/dist/bundle/chunks/{openai-codex-responses-S7CMCAOY.js → openai-codex-responses-LTHOMN37.js} +30 -29
  102. package/dist/bundle/chunks/openai-codex.js +9 -8
  103. package/dist/bundle/chunks/{openai-completions-2Z57N7PC.js → openai-completions-W2X635EE.js} +22 -22
  104. package/dist/bundle/chunks/{openai-decisions-JIOJDB4C.js → openai-decisions-TN2GNOYI.js} +1 -1
  105. package/dist/bundle/chunks/{openai-responses-5VBZSTHL.js → openai-responses-DVY4QXOG.js} +4 -5
  106. package/dist/bundle/chunks/{openrouter-images-S6O7DBEJ.js → openrouter-images-SE2JMS44.js} +1 -1
  107. package/dist/bundle/chunks/openrouter.js +9 -8
  108. package/dist/bundle/chunks/pdfjs-FE3L72A6.js +3662 -0
  109. package/dist/bundle/chunks/{pdfjs-decoders-OFXX4HDZ.js → pdfjs-decoders-VCMCTQJ2.js} +1 -1
  110. package/dist/bundle/chunks/pdfjs-jbig2_nowasm_fallback-I4K6AIV4.js +295 -0
  111. package/dist/bundle/chunks/pdfjs-openjpeg-PYQCV6CM.js +590 -0
  112. package/dist/bundle/chunks/pdfjs-openjpeg_nowasm_fallback-G363SGDI.js +775 -0
  113. package/dist/bundle/chunks/{pi-messages-SMLN5J2W.js → pi-messages-WAS6Z5L5.js} +11 -11
  114. package/dist/bundle/chunks/radius.js +8 -7
  115. package/dist/bundle/chunks/{runtime-OYTWXIUM.js → runtime-H7LYNKCZ.js} +1 -1
  116. package/dist/bundle/chunks/session-picker-XNVLSJ22.js +4 -0
  117. package/dist/bundle/chunks/startup-ui-3TCT465D.js +3 -0
  118. package/dist/bundle/chunks/{trace-command-YLDYCL55.js → trace-command-7ORDQ3JS.js} +4 -4
  119. package/dist/bundle/chunks/{typesafe-system-one-7BEL3H5N.js → typesafe-system-one-AAZH6S3I.js} +1 -1
  120. package/dist/bundle/chunks/{undici-C6S56CGI.js → undici-WVNE45GY.js} +1 -1
  121. package/dist/bundle/chunks/virtual-modules-CIVXCEAN.js +28 -0
  122. package/dist/bundle/cli-runtime.js +5 -5
  123. package/dist/bundle/flow/package.json +5 -5
  124. package/dist/bundle/index.js +13 -13
  125. package/dist/bundle/orchestrate/package.json +22 -6
  126. package/dist/bundle/rpc-entry.js +4 -5
  127. package/dist/cli/args.d.ts.map +1 -1
  128. package/dist/cli/args.js +4 -3
  129. package/dist/cli/args.js.map +1 -1
  130. package/dist/cli/config-selector.d.ts.map +1 -1
  131. package/dist/cli/config-selector.js +9 -6
  132. package/dist/cli/config-selector.js.map +1 -1
  133. package/dist/cli/session-picker.d.ts.map +1 -1
  134. package/dist/cli/session-picker.js +9 -6
  135. package/dist/cli/session-picker.js.map +1 -1
  136. package/dist/cli/startup-ui.d.ts.map +1 -1
  137. package/dist/cli/startup-ui.js +8 -4
  138. package/dist/cli/startup-ui.js.map +1 -1
  139. package/dist/cli.js.map +1 -1
  140. package/dist/core/agent-session-runtime.d.ts +11 -0
  141. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  142. package/dist/core/agent-session-runtime.js +19 -0
  143. package/dist/core/agent-session-runtime.js.map +1 -1
  144. package/dist/core/agent-session-services.d.ts +0 -2
  145. package/dist/core/agent-session-services.d.ts.map +1 -1
  146. package/dist/core/agent-session-services.js +0 -2
  147. package/dist/core/agent-session-services.js.map +1 -1
  148. package/dist/core/agent-session.d.ts +31 -39
  149. package/dist/core/agent-session.d.ts.map +1 -1
  150. package/dist/core/agent-session.js +231 -535
  151. package/dist/core/agent-session.js.map +1 -1
  152. package/dist/core/anthropic-subscription-usage.d.ts +4 -2
  153. package/dist/core/anthropic-subscription-usage.d.ts.map +1 -1
  154. package/dist/core/anthropic-subscription-usage.js +32 -16
  155. package/dist/core/anthropic-subscription-usage.js.map +1 -1
  156. package/dist/core/auto-session-namer.js +1 -1
  157. package/dist/core/auto-session-namer.js.map +1 -1
  158. package/dist/core/cache-warmer.d.ts.map +1 -1
  159. package/dist/core/cache-warmer.js +2 -0
  160. package/dist/core/cache-warmer.js.map +1 -1
  161. package/dist/core/exec.d.ts +1 -0
  162. package/dist/core/exec.d.ts.map +1 -1
  163. package/dist/core/exec.js +4 -1
  164. package/dist/core/exec.js.map +1 -1
  165. package/dist/core/export-html/ansi-to-html.d.ts +6 -1
  166. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  167. package/dist/core/export-html/ansi-to-html.js +57 -20
  168. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  169. package/dist/core/export-html/template.js +1 -1
  170. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  171. package/dist/core/export-html/tool-renderer.js +2 -3
  172. package/dist/core/export-html/tool-renderer.js.map +1 -1
  173. package/dist/core/extensions/loader.d.ts.map +1 -1
  174. package/dist/core/extensions/loader.js +18 -1
  175. package/dist/core/extensions/loader.js.map +1 -1
  176. package/dist/core/extensions/runner.d.ts.map +1 -1
  177. package/dist/core/extensions/runner.js +5 -0
  178. package/dist/core/extensions/runner.js.map +1 -1
  179. package/dist/core/extensions/types.d.ts +5 -0
  180. package/dist/core/extensions/types.d.ts.map +1 -1
  181. package/dist/core/extensions/types.js.map +1 -1
  182. package/dist/core/flow-implementer.d.ts.map +1 -1
  183. package/dist/core/flow-implementer.js +3 -9
  184. package/dist/core/flow-implementer.js.map +1 -1
  185. package/dist/core/keybindings.d.ts +40 -0
  186. package/dist/core/keybindings.d.ts.map +1 -1
  187. package/dist/core/keybindings.js +5 -0
  188. package/dist/core/keybindings.js.map +1 -1
  189. package/dist/core/model-config.d.ts +13 -0
  190. package/dist/core/model-config.d.ts.map +1 -1
  191. package/dist/core/model-registry.d.ts +3 -0
  192. package/dist/core/model-registry.d.ts.map +1 -1
  193. package/dist/core/model-registry.js +32 -8
  194. package/dist/core/model-registry.js.map +1 -1
  195. package/dist/core/model-resolver.d.ts +0 -1
  196. package/dist/core/model-resolver.d.ts.map +1 -1
  197. package/dist/core/model-resolver.js +3 -10
  198. package/dist/core/model-resolver.js.map +1 -1
  199. package/dist/core/model-runtime.d.ts +18 -7
  200. package/dist/core/model-runtime.d.ts.map +1 -1
  201. package/dist/core/model-runtime.js +41 -8
  202. package/dist/core/model-runtime.js.map +1 -1
  203. package/dist/core/oauth-account-pool.d.ts +5 -0
  204. package/dist/core/oauth-account-pool.d.ts.map +1 -1
  205. package/dist/core/oauth-account-pool.js +34 -3
  206. package/dist/core/oauth-account-pool.js.map +1 -1
  207. package/dist/core/package-manager.d.ts +16 -0
  208. package/dist/core/package-manager.d.ts.map +1 -1
  209. package/dist/core/package-manager.js +46 -3
  210. package/dist/core/package-manager.js.map +1 -1
  211. package/dist/core/pi-ai-schemas.d.ts +1 -0
  212. package/dist/core/pi-ai-schemas.d.ts.map +1 -1
  213. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  214. package/dist/core/remote-catalog-provider.js +7 -0
  215. package/dist/core/remote-catalog-provider.js.map +1 -1
  216. package/dist/core/resource-loader.d.ts +5 -1
  217. package/dist/core/resource-loader.d.ts.map +1 -1
  218. package/dist/core/resource-loader.js +2 -0
  219. package/dist/core/resource-loader.js.map +1 -1
  220. package/dist/core/run-outcome.d.ts +6 -3
  221. package/dist/core/run-outcome.d.ts.map +1 -1
  222. package/dist/core/run-outcome.js +36 -9
  223. package/dist/core/run-outcome.js.map +1 -1
  224. package/dist/core/run-preflight.d.ts +1 -1
  225. package/dist/core/run-preflight.d.ts.map +1 -1
  226. package/dist/core/run-preflight.js +19 -11
  227. package/dist/core/run-preflight.js.map +1 -1
  228. package/dist/core/sdk.d.ts +0 -6
  229. package/dist/core/sdk.d.ts.map +1 -1
  230. package/dist/core/sdk.js +7 -16
  231. package/dist/core/sdk.js.map +1 -1
  232. package/dist/core/settings-manager.d.ts +0 -5
  233. package/dist/core/settings-manager.d.ts.map +1 -1
  234. package/dist/core/settings-manager.js +0 -9
  235. package/dist/core/settings-manager.js.map +1 -1
  236. package/dist/core/settings-schema.d.ts +0 -4
  237. package/dist/core/settings-schema.d.ts.map +1 -1
  238. package/dist/core/settings-schema.js +0 -1
  239. package/dist/core/settings-schema.js.map +1 -1
  240. package/dist/core/tools/bash-jobs.d.ts.map +1 -1
  241. package/dist/core/tools/bash-jobs.js +2 -9
  242. package/dist/core/tools/bash-jobs.js.map +1 -1
  243. package/dist/core/tools/find.d.ts.map +1 -1
  244. package/dist/core/tools/find.js +28 -16
  245. package/dist/core/tools/find.js.map +1 -1
  246. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  247. package/dist/core/tools/output-accumulator.js +4 -1
  248. package/dist/core/tools/output-accumulator.js.map +1 -1
  249. package/dist/core/tools/read.d.ts +8 -4
  250. package/dist/core/tools/read.d.ts.map +1 -1
  251. package/dist/core/tools/read.js +10 -15
  252. package/dist/core/tools/read.js.map +1 -1
  253. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  254. package/dist/core/tools/renderers/read.js +6 -2
  255. package/dist/core/tools/renderers/read.js.map +1 -1
  256. package/dist/core/tools/subagent-worktree.d.ts.map +1 -1
  257. package/dist/core/tools/subagent-worktree.js +2 -10
  258. package/dist/core/tools/subagent-worktree.js.map +1 -1
  259. package/dist/core/trace-client/credential-store.d.ts.map +1 -1
  260. package/dist/core/trace-client/credential-store.js +9 -5
  261. package/dist/core/trace-client/credential-store.js.map +1 -1
  262. package/dist/extensions/codemode/execute.js +2 -2
  263. package/dist/extensions/codemode/execute.js.map +1 -1
  264. package/dist/extensions/llama/provider.d.ts +1 -1
  265. package/dist/extensions/llama/provider.d.ts.map +1 -1
  266. package/dist/extensions/llama/provider.js +6 -4
  267. package/dist/extensions/llama/provider.js.map +1 -1
  268. package/dist/extensions/usage/account-reconnect.d.ts +5 -0
  269. package/dist/extensions/usage/account-reconnect.d.ts.map +1 -0
  270. package/dist/extensions/usage/account-reconnect.js +12 -0
  271. package/dist/extensions/usage/account-reconnect.js.map +1 -0
  272. package/dist/extensions/usage/hcode-overview.d.ts +6 -19
  273. package/dist/extensions/usage/hcode-overview.d.ts.map +1 -1
  274. package/dist/extensions/usage/hcode-overview.js +86 -100
  275. package/dist/extensions/usage/hcode-overview.js.map +1 -1
  276. package/dist/extensions/usage/index.d.ts.map +1 -1
  277. package/dist/extensions/usage/index.js +74 -98
  278. package/dist/extensions/usage/index.js.map +1 -1
  279. package/dist/extensions/usage/overview.d.ts +22 -17
  280. package/dist/extensions/usage/overview.d.ts.map +1 -1
  281. package/dist/extensions/usage/overview.js +98 -13
  282. package/dist/extensions/usage/overview.js.map +1 -1
  283. package/dist/extensions/usage/popup.d.ts +9 -14
  284. package/dist/extensions/usage/popup.d.ts.map +1 -1
  285. package/dist/extensions/usage/popup.js +78 -165
  286. package/dist/extensions/usage/popup.js.map +1 -1
  287. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +4 -1
  288. package/dist/humain/flow-command.js +1 -1
  289. package/dist/humain/flow-command.js.map +1 -1
  290. package/dist/humain/flow-loader.d.ts +9 -4
  291. package/dist/humain/flow-loader.d.ts.map +1 -1
  292. package/dist/humain/flow-loader.js +30 -21
  293. package/dist/humain/flow-loader.js.map +1 -1
  294. package/dist/humain/gateway/client.d.ts +3 -1
  295. package/dist/humain/gateway/client.d.ts.map +1 -1
  296. package/dist/humain/gateway/client.js +10 -5
  297. package/dist/humain/gateway/client.js.map +1 -1
  298. package/dist/humain/gateway/login.d.ts.map +1 -1
  299. package/dist/humain/gateway/login.js +160 -53
  300. package/dist/humain/gateway/login.js.map +1 -1
  301. package/dist/humain/hcode/account-store.d.ts +29 -5
  302. package/dist/humain/hcode/account-store.d.ts.map +1 -1
  303. package/dist/humain/hcode/account-store.js +224 -124
  304. package/dist/humain/hcode/account-store.js.map +1 -1
  305. package/dist/humain/hcode/account.d.ts +6 -0
  306. package/dist/humain/hcode/account.d.ts.map +1 -1
  307. package/dist/humain/hcode/account.js +348 -129
  308. package/dist/humain/hcode/account.js.map +1 -1
  309. package/dist/humain/hcode/catalog-watch.d.ts +21 -0
  310. package/dist/humain/hcode/catalog-watch.d.ts.map +1 -0
  311. package/dist/humain/hcode/catalog-watch.js +46 -0
  312. package/dist/humain/hcode/catalog-watch.js.map +1 -0
  313. package/dist/humain/hcode/contracts.d.ts +16 -1
  314. package/dist/humain/hcode/contracts.d.ts.map +1 -1
  315. package/dist/humain/hcode/contracts.js +122 -128
  316. package/dist/humain/hcode/contracts.js.map +1 -1
  317. package/dist/humain/hcode/environment.d.ts +3 -1
  318. package/dist/humain/hcode/environment.d.ts.map +1 -1
  319. package/dist/humain/hcode/environment.js +12 -2
  320. package/dist/humain/hcode/environment.js.map +1 -1
  321. package/dist/humain/hcode/facade.d.ts +26 -6
  322. package/dist/humain/hcode/facade.d.ts.map +1 -1
  323. package/dist/humain/hcode/facade.js +148 -38
  324. package/dist/humain/hcode/facade.js.map +1 -1
  325. package/dist/humain/hcode/http.d.ts +3 -1
  326. package/dist/humain/hcode/http.d.ts.map +1 -1
  327. package/dist/humain/hcode/http.js +44 -23
  328. package/dist/humain/hcode/http.js.map +1 -1
  329. package/dist/humain/hcode/images.d.ts +67 -0
  330. package/dist/humain/hcode/images.d.ts.map +1 -0
  331. package/dist/humain/hcode/images.js +463 -0
  332. package/dist/humain/hcode/images.js.map +1 -0
  333. package/dist/humain/hcode/login-copy.d.ts +28 -0
  334. package/dist/humain/hcode/login-copy.d.ts.map +1 -0
  335. package/dist/humain/hcode/login-copy.js +74 -0
  336. package/dist/humain/hcode/login-copy.js.map +1 -0
  337. package/dist/humain/hcode/login-failure.d.ts +26 -0
  338. package/dist/humain/hcode/login-failure.d.ts.map +1 -0
  339. package/dist/humain/hcode/login-failure.js +50 -0
  340. package/dist/humain/hcode/login-failure.js.map +1 -0
  341. package/dist/humain/hcode/notices.d.ts +24 -1
  342. package/dist/humain/hcode/notices.d.ts.map +1 -1
  343. package/dist/humain/hcode/notices.js +93 -7
  344. package/dist/humain/hcode/notices.js.map +1 -1
  345. package/dist/humain/hcode/provider.d.ts +7 -3
  346. package/dist/humain/hcode/provider.d.ts.map +1 -1
  347. package/dist/humain/hcode/provider.js +123 -19
  348. package/dist/humain/hcode/provider.js.map +1 -1
  349. package/dist/humain/hcode/selection.d.ts +2 -0
  350. package/dist/humain/hcode/selection.d.ts.map +1 -1
  351. package/dist/humain/hcode/selection.js +8 -1
  352. package/dist/humain/hcode/selection.js.map +1 -1
  353. package/dist/humain/hcode/transport.d.ts +13 -10
  354. package/dist/humain/hcode/transport.d.ts.map +1 -1
  355. package/dist/humain/hcode/transport.js +103 -148
  356. package/dist/humain/hcode/transport.js.map +1 -1
  357. package/dist/humain/hcode/wire.d.ts +3 -0
  358. package/dist/humain/hcode/wire.d.ts.map +1 -1
  359. package/dist/humain/hcode/wire.js +11 -0
  360. package/dist/humain/hcode/wire.js.map +1 -1
  361. package/dist/humain/metadata/contracts.d.ts +1 -0
  362. package/dist/humain/metadata/contracts.d.ts.map +1 -1
  363. package/dist/humain/metadata/contracts.js +2 -1
  364. package/dist/humain/metadata/contracts.js.map +1 -1
  365. package/dist/humain/web-access/vendor/anysearch.d.ts.map +1 -1
  366. package/dist/humain/web-access/vendor/anysearch.js +7 -3
  367. package/dist/humain/web-access/vendor/anysearch.js.map +1 -1
  368. package/dist/humain/web-access/vendor/autom.d.ts +4 -0
  369. package/dist/humain/web-access/vendor/autom.d.ts.map +1 -0
  370. package/dist/humain/web-access/vendor/autom.js +191 -0
  371. package/dist/humain/web-access/vendor/autom.js.map +1 -0
  372. package/dist/humain/web-access/vendor/cloro.d.ts +4 -0
  373. package/dist/humain/web-access/vendor/cloro.d.ts.map +1 -0
  374. package/dist/humain/web-access/vendor/cloro.js +236 -0
  375. package/dist/humain/web-access/vendor/cloro.js.map +1 -0
  376. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  377. package/dist/humain/web-access/vendor/curator-page.js +7 -1
  378. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  379. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  380. package/dist/humain/web-access/vendor/curator-server.js +6 -0
  381. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  382. package/dist/humain/web-access/vendor/domain-filter-normalization.d.ts +8 -0
  383. package/dist/humain/web-access/vendor/domain-filter-normalization.d.ts.map +1 -1
  384. package/dist/humain/web-access/vendor/domain-filter-normalization.js +37 -0
  385. package/dist/humain/web-access/vendor/domain-filter-normalization.js.map +1 -1
  386. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts +28 -8
  387. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts.map +1 -1
  388. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js +135 -34
  389. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js.map +1 -1
  390. package/dist/humain/web-access/vendor/duckduckgo.d.ts +1 -1
  391. package/dist/humain/web-access/vendor/duckduckgo.d.ts.map +1 -1
  392. package/dist/humain/web-access/vendor/duckduckgo.js +10 -3
  393. package/dist/humain/web-access/vendor/duckduckgo.js.map +1 -1
  394. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
  395. package/dist/humain/web-access/vendor/extract.js +61 -5
  396. package/dist/humain/web-access/vendor/extract.js.map +1 -1
  397. package/dist/humain/web-access/vendor/gemini-search.d.ts +3 -3
  398. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  399. package/dist/humain/web-access/vendor/gemini-search.js +35 -5
  400. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  401. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  402. package/dist/humain/web-access/vendor/index.js +8 -1
  403. package/dist/humain/web-access/vendor/index.js.map +1 -1
  404. package/dist/humain/web-access/vendor/page-query.d.ts +5 -0
  405. package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
  406. package/dist/humain/web-access/vendor/page-query.js +12 -2
  407. package/dist/humain/web-access/vendor/page-query.js.map +1 -1
  408. package/dist/humain/web-access/vendor/specstream.d.ts +6 -0
  409. package/dist/humain/web-access/vendor/specstream.d.ts.map +1 -0
  410. package/dist/humain/web-access/vendor/specstream.js +253 -0
  411. package/dist/humain/web-access/vendor/specstream.js.map +1 -0
  412. package/dist/humain/web-access/vendor/tool-activation.d.ts.map +1 -1
  413. package/dist/humain/web-access/vendor/tool-activation.js +21 -5
  414. package/dist/humain/web-access/vendor/tool-activation.js.map +1 -1
  415. package/dist/humain/web-access/vendor/upgrade-notice.d.ts +1 -1
  416. package/dist/humain/web-access/vendor/upgrade-notice.js +1 -1
  417. package/dist/humain/web-access/vendor/upgrade-notice.js.map +1 -1
  418. package/dist/humain/web-access/vendor/utils.d.ts +1 -0
  419. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  420. package/dist/humain/web-access/vendor/utils.js +3 -0
  421. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  422. package/dist/humain/web-access/vendor/video-extract.js +2 -2
  423. package/dist/humain/web-access/vendor/video-extract.js.map +1 -1
  424. package/dist/humain/web-access/vendor/web-tool-core.d.ts +13 -0
  425. package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
  426. package/dist/humain/web-access/vendor/web-tool-core.js +16 -5
  427. package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
  428. package/dist/humain/web-access/vendor/youtube-extract.js +2 -2
  429. package/dist/humain/web-access/vendor/youtube-extract.js.map +1 -1
  430. package/dist/index.d.ts +0 -2
  431. package/dist/index.d.ts.map +1 -1
  432. package/dist/index.js.map +1 -1
  433. package/dist/main.d.ts.map +1 -1
  434. package/dist/main.js +96 -28
  435. package/dist/main.js.map +1 -1
  436. package/dist/modes/diagnostics-stderr.d.ts +4 -0
  437. package/dist/modes/diagnostics-stderr.d.ts.map +1 -0
  438. package/dist/modes/diagnostics-stderr.js +11 -0
  439. package/dist/modes/diagnostics-stderr.js.map +1 -0
  440. package/dist/modes/interactive/components/assistant-message.d.ts +1 -1
  441. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  442. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  443. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  444. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  445. package/dist/modes/interactive/components/config-selector.js +5 -2
  446. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  447. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  448. package/dist/modes/interactive/components/extension-selector.js +14 -5
  449. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  450. package/dist/modes/interactive/components/first-time-setup.d.ts +1 -1
  451. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  452. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  453. package/dist/modes/interactive/components/keybinding-hints.d.ts +2 -0
  454. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  455. package/dist/modes/interactive/components/keybinding-hints.js +6 -0
  456. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  457. package/dist/modes/interactive/components/model-selector.d.ts +10 -0
  458. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  459. package/dist/modes/interactive/components/model-selector.js +101 -23
  460. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  461. package/dist/modes/interactive/components/oauth-selector.d.ts +5 -0
  462. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  463. package/dist/modes/interactive/components/oauth-selector.js +17 -6
  464. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  465. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  466. package/dist/modes/interactive/components/radius-login-selector.js +2 -1
  467. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  468. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  469. package/dist/modes/interactive/components/scoped-models-selector.js +13 -6
  470. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  471. package/dist/modes/interactive/components/session-selector.d.ts +8 -1
  472. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  473. package/dist/modes/interactive/components/session-selector.js +41 -9
  474. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  475. package/dist/modes/interactive/components/settings-submenu.d.ts +1 -1
  476. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  477. package/dist/modes/interactive/components/settings-submenu.js +5 -1
  478. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  479. package/dist/modes/interactive/components/status-indicator.d.ts +0 -17
  480. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  481. package/dist/modes/interactive/components/status-indicator.js +1 -78
  482. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  483. package/dist/modes/interactive/components/themed-text.d.ts +1 -1
  484. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  485. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  486. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  487. package/dist/modes/interactive/components/thinking-selector.js +5 -1
  488. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  489. package/dist/modes/interactive/components/tool-execution.d.ts +1 -1
  490. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  491. package/dist/modes/interactive/components/tool-execution.js +3 -1
  492. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  493. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
  494. package/dist/modes/interactive/components/trust-selector.js +14 -5
  495. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  496. package/dist/modes/interactive/components/user-message.d.ts +1 -1
  497. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  498. package/dist/modes/interactive/components/user-message.js.map +1 -1
  499. package/dist/modes/interactive/components/visual-truncate.d.ts +2 -2
  500. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  501. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  502. package/dist/modes/interactive/interactive-mode.d.ts +20 -2
  503. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  504. package/dist/modes/interactive/interactive-mode.js +605 -223
  505. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  506. package/dist/modes/interactive/model-catalog-refresh.d.ts +4 -0
  507. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -1
  508. package/dist/modes/interactive/model-catalog-refresh.js +40 -1
  509. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
  510. package/dist/modes/interactive/oauth-account-format.d.ts +6 -2
  511. package/dist/modes/interactive/oauth-account-format.d.ts.map +1 -1
  512. package/dist/modes/interactive/oauth-account-format.js +12 -3
  513. package/dist/modes/interactive/oauth-account-format.js.map +1 -1
  514. package/dist/modes/interactive/session-share.js +2 -0
  515. package/dist/modes/interactive/session-share.js.map +1 -1
  516. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  517. package/dist/modes/interactive/theme/theme.js +1 -0
  518. package/dist/modes/interactive/theme/theme.js.map +1 -1
  519. package/dist/modes/print-mode.d.ts.map +1 -1
  520. package/dist/modes/print-mode.js +30 -32
  521. package/dist/modes/print-mode.js.map +1 -1
  522. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  523. package/dist/modes/rpc/rpc-mode.js +26 -39
  524. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  525. package/dist/modes/rpc/rpc-types.d.ts +1 -0
  526. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  527. package/dist/modes/rpc/rpc-types.js.map +1 -1
  528. package/dist/package-manager-cli.d.ts.map +1 -1
  529. package/dist/package-manager-cli.js +14 -1
  530. package/dist/package-manager-cli.js.map +1 -1
  531. package/dist/utils/abort.d.ts +5 -0
  532. package/dist/utils/abort.d.ts.map +1 -1
  533. package/dist/utils/abort.js +9 -0
  534. package/dist/utils/abort.js.map +1 -1
  535. package/dist/utils/changelog.d.ts.map +1 -1
  536. package/dist/utils/changelog.js +3 -2
  537. package/dist/utils/changelog.js.map +1 -1
  538. package/dist/utils/flush-stdout.d.ts +8 -0
  539. package/dist/utils/flush-stdout.d.ts.map +1 -0
  540. package/dist/utils/flush-stdout.js +23 -0
  541. package/dist/utils/flush-stdout.js.map +1 -0
  542. package/dist/utils/image-process.d.ts +2 -0
  543. package/dist/utils/image-process.d.ts.map +1 -1
  544. package/dist/utils/image-process.js +3 -3
  545. package/dist/utils/image-process.js.map +1 -1
  546. package/dist/utils/image-resize-core.js +2 -2
  547. package/dist/utils/image-resize-core.js.map +1 -1
  548. package/dist/utils/shell.d.ts +2 -0
  549. package/dist/utils/shell.d.ts.map +1 -1
  550. package/dist/utils/shell.js +19 -0
  551. package/dist/utils/shell.js.map +1 -1
  552. package/docs/cli.md +1 -1
  553. package/docs/development.md +0 -13
  554. package/docs/extensions.md +6 -4
  555. package/docs/flow.md +4 -62
  556. package/docs/humain-code-forge-architecture.md +1 -47
  557. package/docs/humain-code-forge-flow-walkthrough.md +1 -1
  558. package/docs/humain-code.md +1 -1
  559. package/docs/keybindings.md +2 -0
  560. package/docs/llama-cpp.md +5 -5
  561. package/docs/models-configuration.md +4 -2
  562. package/docs/nvidia-rtx-llama-cpp.md +5 -5
  563. package/docs/providers.md +14 -9
  564. package/docs/rpc-commands.md +1 -1
  565. package/docs/run-preflight.md +1 -1
  566. package/docs/slash-commands.md +1 -1
  567. package/docs/tui.md +2 -0
  568. package/examples/README.md +0 -3
  569. package/examples/extensions/custom-provider-anthropic/package-lock.json +4 -4
  570. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  571. package/examples/extensions/gondolin/index.ts +4 -7
  572. package/examples/tsconfig.json +96 -76
  573. package/npm-shrinkwrap.json +285 -764
  574. package/package.json +24 -37
  575. package/schemas/keybindings.schema.json +20 -0
  576. package/schemas/models.schema.json +5 -1
  577. package/schemas/settings.schema.json +0 -13
  578. package/src/humain/web-access/UPSTREAM.md +52 -1
  579. package/src/humain/web-access/upstream.json +5 -5
  580. package/src/humain/web-access/vendor/CHANGELOG.md +29 -0
  581. package/dist/bundle/chunks/adaptive-peer-worker-X2ZNZE3S.js +0 -8
  582. package/dist/bundle/chunks/adaptive-session-host-7KDSQV5I.js +0 -162
  583. package/dist/bundle/chunks/anthropic-messages-TQK3FUV3.js +0 -68
  584. package/dist/bundle/chunks/azure-openai-responses-JY7OSLH2.js +0 -15
  585. package/dist/bundle/chunks/chunk-5L4PBYC7.js +0 -11
  586. package/dist/bundle/chunks/chunk-6PNQYO6A.js +0 -10
  587. package/dist/bundle/chunks/chunk-CRN54O4D.js +0 -24
  588. package/dist/bundle/chunks/chunk-CTU2ECLD.js +0 -7
  589. package/dist/bundle/chunks/chunk-DBL35X7L.js +0 -3
  590. package/dist/bundle/chunks/chunk-GME4AWDG.js +0 -23
  591. package/dist/bundle/chunks/chunk-GTILMMUF.js +0 -12
  592. package/dist/bundle/chunks/chunk-J57HOSWD.js +0 -21
  593. package/dist/bundle/chunks/chunk-KQM7ZGL6.js +0 -11
  594. package/dist/bundle/chunks/chunk-MX4Q4W6H.js +0 -214
  595. package/dist/bundle/chunks/chunk-NXA6NEHE.js +0 -54
  596. package/dist/bundle/chunks/chunk-PJACZCIR.js +0 -2
  597. package/dist/bundle/chunks/chunk-T5A6T24H.js +0 -93
  598. package/dist/bundle/chunks/chunk-WCFHG6NO.js +0 -16
  599. package/dist/bundle/chunks/chunk-ZJUU6WOV.js +0 -2052
  600. package/dist/bundle/chunks/compat-ZK2DIW3P.js +0 -15
  601. package/dist/bundle/chunks/dist-EY7YKQHB.js +0 -11
  602. package/dist/bundle/chunks/dist-J5IUPLMH.js +0 -37
  603. package/dist/bundle/chunks/dist-cjs-2SKN226B.js +0 -184
  604. package/dist/bundle/chunks/entry-AL54ZGYO.js +0 -2
  605. package/dist/bundle/chunks/es5-GYTRHFKS.js +0 -77
  606. package/dist/bundle/chunks/google-generative-ai-UL7YEQ6J.js +0 -21
  607. package/dist/bundle/chunks/google-vertex-OTMSPUYH.js +0 -26
  608. package/dist/bundle/chunks/host-75YAHLDR.js +0 -3
  609. package/dist/bundle/chunks/interactive-mode-IW4PIVAQ.js +0 -5
  610. package/dist/bundle/chunks/mistral-conversations-E72Y6OC3.js +0 -43
  611. package/dist/bundle/chunks/pdfjs-AKD6EBKN.js +0 -3614
  612. package/dist/bundle/chunks/pdfjs-jbig2_nowasm_fallback-FH3KJM4H.js +0 -326
  613. package/dist/bundle/chunks/pdfjs-openjpeg-SKR7C34X.js +0 -671
  614. package/dist/bundle/chunks/pdfjs-openjpeg_nowasm_fallback-VUBL7UEE.js +0 -974
  615. package/dist/bundle/chunks/session-picker-DM6S37IF.js +0 -4
  616. package/dist/bundle/chunks/startup-ui-4GGLWNSU.js +0 -3
  617. package/dist/bundle/chunks/virtual-modules-TI3W24YL.js +0 -28
  618. package/dist/core/internal-process.d.ts +0 -23
  619. package/dist/core/internal-process.d.ts.map +0 -1
  620. package/dist/core/internal-process.js +0 -88
  621. package/dist/core/internal-process.js.map +0 -1
  622. package/dist/humain/adaptive-execution.d.ts +0 -51
  623. package/dist/humain/adaptive-execution.d.ts.map +0 -1
  624. package/dist/humain/adaptive-execution.js +0 -100
  625. package/dist/humain/adaptive-execution.js.map +0 -1
  626. package/dist/humain/adaptive-peer-process.d.ts +0 -44
  627. package/dist/humain/adaptive-peer-process.d.ts.map +0 -1
  628. package/dist/humain/adaptive-peer-process.js +0 -159
  629. package/dist/humain/adaptive-peer-process.js.map +0 -1
  630. package/dist/humain/adaptive-peer-worker.d.ts +0 -3
  631. package/dist/humain/adaptive-peer-worker.d.ts.map +0 -1
  632. package/dist/humain/adaptive-peer-worker.js +0 -122
  633. package/dist/humain/adaptive-peer-worker.js.map +0 -1
  634. package/dist/humain/adaptive-runtime-types.d.ts +0 -621
  635. package/dist/humain/adaptive-runtime-types.d.ts.map +0 -1
  636. package/dist/humain/adaptive-runtime-types.js +0 -3
  637. package/dist/humain/adaptive-runtime-types.js.map +0 -1
  638. package/dist/humain/adaptive-session-host.d.ts +0 -113
  639. package/dist/humain/adaptive-session-host.d.ts.map +0 -1
  640. package/dist/humain/adaptive-session-host.js +0 -1838
  641. package/dist/humain/adaptive-session-host.js.map +0 -1
  642. package/dist/utils/deprecation.d.ts +0 -4
  643. package/dist/utils/deprecation.d.ts.map +0 -1
  644. package/dist/utils/deprecation.js +0 -13
  645. package/dist/utils/deprecation.js.map +0 -1
  646. package/examples/plugins/pi-example-plugin/README.md +0 -38
  647. package/examples/plugins/pi-example-plugin/package.json +0 -10
  648. package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
  649. package/examples/plugins/pi-example-plugin/src/session.ts +0 -24
  650. package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
package/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # Changelog
2
2
 
3
+ ## [Unreleased]
4
+
5
+ ## [0.8.0] - 2026-11-22
6
+
7
+ ### Breaking Changes
8
+
9
+ - Extension components: `render()` now returns `readonly string[]` and `Container` returns the same cached array while its children are unchanged (Pi 1.6.0). Extensions that modify render output in place, including `super.render()` in a `Container` subclass, must copy it first.
10
+ - Removed the never-enabled experimental adaptive-v2 engine and its SDK hooks (no known consumers). The SDK no longer accepts `executionEngine`, `adaptiveExecution` or `PromptOptions.adaptiveStartingLevel`; `AgentSession.executionEngine`, `adaptiveCompletion`, `rereadAdaptiveCompletion()`, the `adaptive_status`/`adaptive_completion` session events and the exported adaptive types are gone. Direct prompts, `/flow` and `/orchestrate` are unchanged ([#169](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/169)).
11
+
12
+ ### Changed
13
+
14
+ - Synced the upstream Pi baseline to 1.6.0: GPT-6.2 Sol is the default model for `openai`, `azure` and `openai-codex`; `find` path patterns are relative to the search directory; Anthropic message threads are on by default when the provider baseUrl host is `api.anthropic.com`. Also updated pi-web-access to 0.48.0, the Claude Code, Codex and VS Code client identities to 2.1.330, 0.171.0 and 1.147.0, and all direct dependencies to their latest releases. See `docs/upstream-refresh-20261121.md`.
15
+ - HUMAIN Code sign-in failures now name the failing stage with fixed text (configuration, issuer discovery, device authorization, account request, account response, account details, account environment, local secure storage, account reference) instead of the generic credential-operation message; storage and reference failures keep the possible-state-change warning ([#110](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/110)).
16
+ - Print/JSON and RPC runs on a managed HUMAIN Code model no longer send a metered readiness probe: preflight checks sign-in only, and the task request is the first inference. Agent-exec and in-process Flow still probe ([#188](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/188), [!129](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/merge_requests/129)).
17
+ - Headless runs load the HUMAIN Code catalog when `--provider humain-code-account` or `--model humain-code-account/...` is given explicitly ([#188](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/188), [!129](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/merge_requests/129)).
18
+
19
+ ### Fixed
20
+
21
+ - HUMAIN Code no longer breaks when the server adds a field or rewords an error: sign-in, the model catalog, `/usage`, streamed replies and metadata delivery ignore unknown response fields, a reworded refusal is shown as its code's refusal instead of "may still be charged", `hcode_busy` shows the server's real retry time, and `/usage` shows the server's totals as sent instead of blanking on an arithmetic mismatch. What the CLI sends is still checked strictly ([#198](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/198)).
22
+ - A HUMAIN Code sign-in is shared by every `humain-code` process for the same environment: a terminal opened later starts signed in, and `/login` and `/model` pick up a sign-in or sign-out made in another terminal. When this terminal's environment has no sign-in but another one does (for example a DEV sign-in and a terminal started without `--env`), startup and `/login status` say which `--env` to use ([#188](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/188)).
23
+ - HUMAIN Code keeps the saved sign-in when refresh fails or is cancelled. If the issuer may have consumed the refresh token, the CLI retains the saved grant without replaying the token and prompts for a new sign-in. Device sign-in tolerates brief network interruptions and no longer blocks other windows while waiting for approval ([#194](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/194)).
24
+ - HUMAIN Code fits screenshots and images from tools or conversation history to the selected model’s limits. If a request still exceeds the limit, it omits older images first and reports what was left out, without changing originals in the saved transcript ([#197](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/197)).
25
+ - Stabilized release verification by reducing timing sensitivity in redaction, tool-call highlighting, and Flow QA and telemetry tests (!146).
26
+ - Fixed the standalone Bun build to build its own prerequisites without depending on removed workspaces, and corrected the plugin documentation (!144).
27
+ - HUMAIN Code refusals that Forge makes before running a request (invalid request, unsupported capability, model unavailable, access, sign-in, terms) no longer say the request "may still be charged". They say why in plain words, using Forge's reason when it sends one (for example "HUMAIN Code's provider key is set to a region this model can't run in" or "This model can't replay thinking from earlier turns"), and that nothing was charged. The uncertain-outcome warning remains for failures after submission ([#196](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/196)).
28
+ - Switching to a HUMAIN Code model mid-conversation no longer gets the next request refused: thinking, signatures and thinking levels from other models are left out of what is sent, and other providers' tool-call IDs are rewritten consistently. The saved conversation is unchanged.
29
+ - Headless runs with `--provider humain-code-account` load the account catalog with its own time budget, so a slow HUMAIN Node or Gateway discovery no longer leaves the selected model "unavailable". A HUMAIN Code selection refused during headless setup (such as an unsupported `--thinking` level) now prints its fixed reason instead of exiting with only `failureClass: setup`; other setup errors stay unprinted.
30
+ - Fixed Claude subscription usage retrying after 1 s instead of 5 min when a 429 carries a junk `Retry-After` such as `-1` or `120.5` ([#167](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/167)).
31
+ - Listed `fix` in the `/flow` command description, and stopped advertising `--fan-out` in `/flow` help and the Flow docs; it is still accepted but has no effect ([#167](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/167)).
32
+ - Fixed the npm shrinkwrap and install lock declaring `typebox` 1.4.7 for `@humain/humain-code-contracts` 0.4.21, whose published tarball depends on 1.4.6. Both locks now match the tarball, and release checks compare lock metadata with the published tarball, not only its integrity.
33
+ - The CLI now depends on `@humain/humain-code-contracts` 0.4.22, which carries the wider Flow `route_bound.effort` (`xhigh`, `max`) from [#133](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/133) and `typebox` 1.4.7. Published 0.4.21 is immutable and lacked that change, so tag CI would have refused the release. Publish contracts 0.4.22 before the CLI (tag CI does this in order).
34
+ - An empty HUMAIN Code model list after sign-in now says why and what to do when Forge sends a reason (no model approved for CLI, provider key not enabled for CLI, or CLI setup not finished on the server), instead of always saying the admin hasn't enabled CLI models ([#176](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/176)).
35
+ - HUMAIN Code sign-in with no models no longer traps you in a Retry/Cancel dialog: you return to the prompt with a notice naming the reason and who can fix it, your current model is kept, the status line shows `HUMAIN Code: signed in · 0 models`, the catalog is re-checked every 60 s for 10 minutes and new models are announced; `/model` shows an empty HUMAIN Code row with the reason and Retry, and `/login status` shows the details ([#188](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/188)).
36
+ - `/login` shows HUMAIN Code at once with a live `checking connection…` state, verified against `/api/cli/config` and issuer discovery, pre-warmed at startup and cached for 5 minutes; selecting it while checking waits inline and continues, and failures say `Can't reach <host>: check VPN/Zscaler` or that the server's sign-in settings don't match this CLI, with Retry ([#188](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/188)).
37
+ - HUMAIN Code device-code polling retries DNS, connection, timeout and 5xx errors with backoff until the code expires. Sign-in names the actual failure, such as cancellation, a concurrent account change, denial, expiry, issuer mismatch or an unexpected reply ([#188](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/188)).
38
+ - `/model` keeps your current thinking level when the new model supports it and tells you if it must adjust. `/thinking` changes effort separately. Pasting an image on a text-only model offers to send the draft without it and lists image-capable alternatives.
39
+ - HUMAIN Code requests use supported thinking levels and omit older reasoning from other providers when the selected model cannot accept it.
40
+ - The HUMAIN Code `/usage` tab shows concise monthly totals and the dashboard link; press `d` for the five most recent requests.
41
+ - Fixed HUMAIN Code prompt refusals for models loaded from the local v1 catalog by sending supported request fields with their tools ([#188](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/188), [!129](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/merge_requests/129)).
42
+ - Selecting a HUMAIN Code model when the live sign-in check fails now says so and points to `/login`, instead of reporting a changed catalog or account; the current model and transcript are kept ([#188](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/188)).
43
+ - Switched HUMAIN Gateway sign-in to PKCE for local browser and remote paste-code flows ([#181](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/181)).
44
+ - Fixed stale Claude subscription usage and refresh after changing accounts in a pool ([#183](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/183)).
45
+ - Restored first-signal shutdown while cleaning up subprocesses started by multiple CLI subsystems ([#164](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/164)).
46
+ - Headless preflight and settled runs classify the provider's structured HTTP status before its message text, so 401/403 responses exit as auth (20) and other provider errors as provider (21) even when their text contains those digits ([#180](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/180)).
47
+ - Corrected Flow cost accounting for bare Bedrock model IDs, recorded expanded nested Flow effort, and preserved admitted IDs in early Flow refusals ([#184](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/184), [#133](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/133), [#178](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/178)).
48
+ - The Flow status board, Trust, Extension and scoped-model selectors honor configured navigation, confirm and cancel keybindings and show the resolved key hints; closing the Flow board leaves the run in progress ([#122](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/122)).
49
+ - Faster streaming render of large tables: only cells that overflow their column are wrapped and memoized ([#103](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/103)).
50
+ - Released abandoned Chord registry views ([#123](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/123)).
51
+ - Fixed Linux trace credential lookup and removal treating Secret Service failures as missing credentials ([#165](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/165)).
52
+ - Updated the eval runners to accept CLI 0.7.0 settled outcomes and contracts 0.4.21. For gated runs, exit 25 or 26 with a valid settled outcome counts as a completion claim, not a verification pass ([#172](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/172), [#173](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/173), [#174](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/174)).
53
+ - A HUMAIN Code request refused before sending now names the reason and says "No request was sent or charged."; required strict tool sampling fails closed with that notice ([#188](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/188), [!129](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/merge_requests/129)).
54
+
55
+ ### Removed
56
+
57
+ - Removed the experimental remote harness (the `PI_EXPERIMENTAL=1` server/client commands, the `./client` and `./experimental/plugin` source-only subpaths, and the `pi-client`, `pi-server` and `pi-protocol` packages). It ran only from a source checkout and never shipped, so installed CLIs are unaffected. Chord now follows upstream Pi 1.6.0, and the package no longer depends on `@earendil-works/chord` or `esbuild`. HUMAIN `/remote` is unchanged.
58
+ - Removed the `executionEngine` and `adaptiveExecution` settings. Existing settings files that still set them load and are ignored. Sessions saved by `adaptive-v2` still open with their transcript intact and continue as ordinary direct prompts; their adaptive records stay in the file but are no longer read or resumed ([#169](https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/issues/169)).
59
+
3
60
  ## [0.7.0] - 2026-11-17
4
61
 
5
62
  ### New Features
@@ -794,6 +851,88 @@ Version 0.4.16 was never published to npm and is superseded by 0.4.17. This rele
794
851
  - Removed the vendored `pi-mcp-adapter` bundle, its upstream check and bundle scripts (see Breaking Changes).
795
852
  - Removed the `@humain/terminal` extension import alias (see Breaking Changes).
796
853
 
854
+ ## [1.6.0] - 2026-11-20
855
+
856
+ ### New Features
857
+
858
+ - **GPT-6.2 Astra and GPT-6.2 Sol**: both models are available on the `openai`, `azure`, and `openai-codex` providers, and GPT-6.2 Sol is now the default model for all three. See [Providers](docs/providers.md).
859
+
860
+ ### Breaking Changes
861
+
862
+ - Extension components: `render()` now returns `readonly string[]`, and `Container` returns the same cached array while its children are unchanged. Extensions that modify render output in place, including `super.render()` in a `Container` subclass or an embedded component's output, must copy it first ([#9549](https://github.com/earendil-works/pi/issues/9549))
863
+
864
+ ### Added
865
+
866
+ - Added GPT-6.2 Astra and GPT-6.2 Sol to the `openai`, `azure`, and `openai-codex` providers. Both reject reasoning effort `none` and `minimal`, so thinking level `off` is unavailable. Azure serves them with a 1.05M context window; Codex serves GPT-6.2 Sol with 500K and GPT-6.2 Astra with 272K
867
+ - Added `qwen4-max-preview` to the Qwen Token Plan Individual providers ([#12259](https://github.com/earendil-works/pi/issues/12259))
868
+ - Added `deepseek-v4.1-flash` and `deepseek-v4.1-flash-1017` to the Qwen Token Plan Individual providers, and per-plan key variables `QWEN_TOKEN_PLAN_TEAM_API_KEY`, `QWEN_TOKEN_PLAN_TEAM_CN_API_KEY`, `QWEN_TOKEN_PLAN_INDIVIDUAL_API_KEY`, and `QWEN_TOKEN_PLAN_INDIVIDUAL_CN_API_KEY`; the shared `QWEN_TOKEN_PLAN_API_KEY` and `QWEN_TOKEN_PLAN_CN_API_KEY` still work ([#11773](https://github.com/earendil-works/pi/issues/11773))
869
+ - Added a transcript notice when OpenAI drops reasoning items from a request, such as `OpenAI dropped 2 reasoning items: prefix_mismatch (details in session)` after compaction on GPT-6.2. Like the Anthropic thinking notice, it is shown when `showCacheMissNotices` is on and only when more items are dropped than in the previous response. Both notices now name the reasons
870
+
871
+ ### Changed
872
+
873
+ - Qwen Token Plan providers now use the current gateways (`token-plan.maas.qwencloudapi.com` international, `token-plan.maas.qianwenaiapi.com` China), and `qwen-token-plan` and `qwen-token-plan-cn` are named "Qwen Token Plan Team" and "Qwen Token Plan Team CN". Provider IDs are unchanged, and the old `aliyuncs.com` hosts still work ([#11773](https://github.com/earendil-works/pi/issues/11773))
874
+ - Updated `undici` to 8.12.4 for security advisories GHSA-mqg3-3v4r-cm32, GHSA-7xg3-fphp-28hg, GHSA-5rm8-gv32-r954, GHSA-9v6h-8rgp-m69f, GHSA-3g9m-rv3r-w5w2, and GHSA-r4pc-4jcp-7pqc ([#12200](https://github.com/earendil-works/pi/issues/12200))
875
+ - The default model for the `openai`, `azure`, and `openai-codex` providers is now GPT-6.2 Sol (`gpt-6.2-sol`) instead of GPT-6.1 Sol, at the same price
876
+ - The find tool's path patterns are now relative to the search directory, like grep's `glob`: `src/*.ts` finds `src/a.ts` but no longer `pkg/src/a.ts`; use `**/src/*.ts` to match at any depth. Patterns without `/` still match file names at any depth ([#12066](https://github.com/earendil-works/pi/issues/12066))
877
+ - The llama.cpp extension now connects to `http://127.0.0.1:9931` by default, the current llama-server default port, instead of port 8080 ([#12001](https://github.com/earendil-works/pi/pull/12001) by [@julien-c](https://github.com/julien-c))
878
+ - Anthropic message threads are now on by default for any provider whose baseUrl is on api.anthropic.com, not only the `anthropic` provider ([#11987](https://github.com/earendil-works/pi/issues/11987))
879
+ - The resume command printed on exit is now on its own line after `To resume this session:`, so it can be selected with a triple-click ([#12237](https://github.com/earendil-works/pi/issues/12237))
880
+
881
+ ### Fixed
882
+
883
+ - Fixed `read` storing a note that the current model does not support images, which was replayed to the model as stale text after switching to a vision model. The image is still replaced with a placeholder per request for models without image input, and the read result now shows the warning in the TUI only, also when collapsed ([#12131](https://github.com/earendil-works/pi/issues/12131))
884
+ - Fixed MCP tools loaded by `tool_search` being dropped on resume and `/reload` when an extension deactivates only its own tool at `session_start`, as pi-web-access and pi-subagents do in `toolActivation: "auto"` mode ([#11996](https://github.com/earendil-works/pi/issues/11996))
885
+ - Fixed the standalone binary failing to resolve extension npm dependencies whose entry point is declared in `package.json` `main` or `exports` (for example `shiki`, `yaml`, `graceful-fs`), including imports made from inside other dependencies ([#12012](https://github.com/earendil-works/pi/issues/12012))
886
+ - Fixed the find tool returning no results for patterns starting with `./`, such as `./src/*.ts` ([#12020](https://github.com/earendil-works/pi/issues/12020))
887
+ - Fixed pi exiting with an uncaught `AbortError` when a `read` tool call is cancelled while the file is being opened ([#11956](https://github.com/earendil-works/pi/issues/11956))
888
+ - Fixed pi exiting with an uncaught `AbortError` when the session picker cancels loading after skipping a `.jsonl` file that is not a session, and fixed such files staying open ([#11956](https://github.com/earendil-works/pi/issues/11956))
889
+ - Fixed `/share` crashing pi when the GitHub CLI fails to start
890
+ - Fixed `pi update` on Windows managed installs failing with "Could not verify managed Pi" when an older system Node.js comes before the installer's standalone Node.js on PATH ([#12048](https://github.com/earendil-works/pi/issues/12048))
891
+ - Fixed `/export` HTML showing raw terminal hyperlink escape codes around links in custom tool output; links are now clickable ([#12003](https://github.com/earendil-works/pi/issues/12003))
892
+ - Fixed the bash tool returning no output, with a footer like `[Showing lines 3-2 of 2]`, when the output ends in one line longer than about 100KB, such as a `grep` match in a minified file; it now shows the end of that line ([#12062](https://github.com/earendil-works/pi/issues/12062))
893
+ - Fixed provider errors reading "Connection closed." not triggering automatic retries ([#12064](https://github.com/earendil-works/pi/issues/12064))
894
+ - Fixed `/resume` sometimes selecting an unrelated session while the list reloads after deleting or renaming a session ([#12106](https://github.com/earendil-works/pi/issues/12106))
895
+ - Fixed Groq Qwen models failing with `400 Unexpected message role`; OpenAI-compatible providers other than OpenAI now receive system messages (the system prompt and mid-conversation system messages) with the `system` role ([#10741](https://github.com/earendil-works/pi/issues/10741))
896
+ - Fixed `enabledModels`/`--models` warnings such as `No models match pattern "github-copilot/nope"` being written over the interactive TUI on every `/new`, `/resume` and `/fork`, which left stale lines in fullscreen mode. The warnings are now shown once at startup, in the chat in interactive mode and on stderr in other modes; RPC mode no longer repeats them on stderr for each `new_session`, `switch_session` or `fork` ([#11264](https://github.com/earendil-works/pi/issues/11264))
897
+ - Fixed the find tool matching path patterns through folders above the search path: with the project in `~/src/app`, `src/**/*.ts` returned every `.ts` file in the project ([#12066](https://github.com/earendil-works/pi/issues/12066))
898
+ - Fixed pi crashing with `RangeError: Maximum call stack size exceeded` when rendering a very large edit diff, for example after editing a file with a multi-megabyte line, and again on every resume of that session ([#8036](https://github.com/earendil-works/pi/issues/8036))
899
+ - Fixed pressing Esc during a batch of tool calls leaving the calls that had not started yet without a result in the session; they now get an "Operation aborted" result ([#9986](https://github.com/earendil-works/pi/issues/9986))
900
+ - Fixed an unreadable `CHANGELOG.md` (pi's own or an extension package's) printing `Warning: Could not parse changelog` over the interactive TUI; it now shows no changelog notes ([#11264](https://github.com/earendil-works/pi/issues/11264))
901
+ - Fixed problems found when replacing the session with `/new`, `/resume`, `/fork` or RPC `new_session`, `switch_session` and `fork` never being shown, for example a project extension that fails to load after `/resume` into another project, or an `enabledModels` pattern that matches nothing after a settings change. Interactive mode now shows them in the chat and print, JSON and RPC modes write them to stderr; a problem already reported is not repeated. SDK hosts can call the new `AgentSessionRuntime.takeUnreportedDiagnostics()` at startup and after each replacement to get each diagnostic once
902
+ - Fixed RPC `new_session`, `switch_session`, `fork` and `clone` running extension `session_start` and `resources_discover` handlers twice for the new session. RPC clients now also receive events emitted by `session_start` handlers, such as `entry_appended` for entries they append ([#10470](https://github.com/earendil-works/pi/issues/10470))
903
+ - Fixed an exception thrown by an extension's `pi.events` handler being printed with `console.error` over the interactive TUI. It is now reported like other extension errors: in the chat in interactive mode, as `extension_error` in RPC mode and as `Extension error (...)` in print mode. Errors from a handler that fails after its session was replaced are dropped ([#11264](https://github.com/earendil-works/pi/issues/11264))
904
+ - Fixed `AgentSession.reload()` not emitting `session_start` to extensions when the SDK host bound them with `bindExtensions({})`, after it had already emitted `session_shutdown`. Extensions that start work in `session_start`, such as the MCP extension connecting its servers, stayed stopped after a reload
905
+ - Fixed `--mode json` dropping events emitted by extension `session_start` handlers, such as `entry_appended` for entries they append, at startup and after an extension replaces the session
906
+ - Fixed `Could not restore model <provider>/<model>. Using <fallback>` being shown only at interactive startup. Resuming or forking into a session whose model no longer exists or has no login switched to another model without notice, and print, JSON and RPC modes never showed it. It is now reported in every mode, at startup and after `/resume`, `/fork` and RPC `switch_session` or `fork`
907
+ - Fixed git and npm output, such as `Cloning into ...` or `added 12 packages`, being drawn over the interactive TUI when pi installed or refreshed packages during `/reload`, `/new`, `/resume` and `/fork`, including temporary `-e git:` and `-e npm:` packages. In interactive mode their output is now captured, and a failed install reports the end of it. Until the TUI starts, each install is announced as `Installing <source>...` on stderr instead of showing git and npm output. git and ssh can no longer prompt in interactive mode: a package that needs a typed password or passphrase fails with a hint to set up a credential helper or ssh agent, or to run `pi install <source>` once from the shell. `pi install` and `pi update` keep live output ([#11264](https://github.com/earendil-works/pi/issues/11264))
908
+ - Fixed fullscreen scrolling in long sessions saturating a CPU core by re-rendering the whole transcript on every wheel event ([#9549](https://github.com/earendil-works/pi/issues/9549))
909
+ - Fixed search in `/login`, `/logout`, `/scoped-models` and `/resume` keeping the highlight on the row scrolled to before typing, so Enter picked whichever entry landed there instead of the best match; a query now highlights the top match, as `/model` does ([#12245](https://github.com/earendil-works/pi/issues/12245), [#12246](https://github.com/earendil-works/pi/pull/12246) by [@acmerfight](https://github.com/acmerfight))
910
+ - Fixed exiting pi, `pi config` and the `--resume` and other startup pickers dropping terminal output still queued in stdout, such as the resets that turn off mouse tracking and Kitty keyboard reporting; the shell could then print mouse and key reports as text. pi now waits up to one second for queued output before exiting or continuing ([#12133](https://github.com/earendil-works/pi/issues/12133))
911
+ - Fixed moving the cursor in a search field with Left, Right, Home or End moving the highlight back to the first entry in `/login`, `/logout`, `/model`, `/scoped-models`, `/resume`, `/settings`, the per-model settings model picker and `pi config` ([#12245](https://github.com/earendil-works/pi/issues/12245))
912
+ - Fixed llama.cpp decision classifiers ignoring the image input that llama.cpp reports, such as Clef with its `mmproj`; `models.classify()` now sends their images to `/v1/systemone` ([#12282](https://github.com/earendil-works/pi/issues/12282))
913
+ - Fixed `kill -TSTP` from outside pi stopping it without restoring the terminal, which left mouse tracking and the Kitty keyboard protocol on at the shell prompt and turned mouse movement into garbage input. pi now suspends as with Ctrl+Z and redraws on `fg` ([#12283](https://github.com/earendil-works/pi/pull/12283) by [@haoqixu](https://github.com/haoqixu))
914
+ - Fixed changing the thinking level on the `openai-codex` provider invalidating the prompt cache on GPT-6 models ([#12269](https://github.com/earendil-works/pi/issues/12269))
915
+ - Fixed unscoped syntax-highlighted text inheriting the terminal foreground and becoming unreadable on contrasting tool cards ([#11092](https://github.com/earendil-works/pi/issues/11092))
916
+ - Fixed `/copy` saying "No agent messages to copy yet." after Esc during a tool call or after a provider error; it now copies the previous answer. RPC `get_last_assistant_text` skips the same messages ([#12119](https://github.com/earendil-works/pi/issues/12119), [#12121](https://github.com/earendil-works/pi/pull/12121) by [@acmerfight](https://github.com/acmerfight))
917
+ - Fixed `pi.exec` reporting exit code 0 for commands ended by a signal, such as a timeout, an abort or a crash; it now reports 128 + the signal number, like a shell (143 for SIGTERM, 137 for SIGKILL) ([#12088](https://github.com/earendil-works/pi/issues/12088), [#12089](https://github.com/earendil-works/pi/pull/12089) by [@acmerfight](https://github.com/acmerfight))
918
+ - Fixed GitHub Copilot Gemini and Kimi models (`gemini-4-argon`, `gemini-4-carbon`, `gemini-3.8-flash`, `kimi-k3`) ignoring the thinking level, and Copilot usage always reporting 0 reasoning tokens ([#12110](https://github.com/earendil-works/pi/pull/12110) by [@DenielC1](https://github.com/DenielC1))
919
+ - Fixed provider errors that report only a Node socket error code, such as `read ECONNRESET`, `write EPIPE`, or `connect ETIMEDOUT`, not triggering automatic retries ([#12128](https://github.com/earendil-works/pi/issues/12128))
920
+ - Fixed OpenAI rejecting requests with a 400 error when a tool's schema contains a node without a `type` (such as `items: {}` or `Type.Unknown()`); such tools are now sent in non-strict mode ([#12049](https://github.com/earendil-works/pi/issues/12049))
921
+ - Fixed Mistral Large 4 tool calls stalling for minutes; Mistral models no longer receive strict tools unless `compat.supportsStrictMode` is set ([#12148](https://github.com/earendil-works/pi/issues/12148))
922
+ - Fixed non-strict Anthropic tool schemas not telling the model that extra arguments are forbidden ([#12067](https://github.com/earendil-works/pi/issues/12067))
923
+ - Fixed GitHub Copilot models on the Responses API (GPT, Grok, MAI-Code) filling omitted optional tool arguments with empty strings or invented values ([#12286](https://github.com/earendil-works/pi/issues/12286))
924
+ - Fixed the OpenAI Codex WebSocket 60-minute connection limit failing the turn when it hit mid-stream, for example during long thinking; the request is now retried on a fresh connection ([#12124](https://github.com/earendil-works/pi/issues/12124))
925
+ - Fixed the `openai-codex` provider getting almost no prompt cache hits for the system prompt on GPT-6.2 models ([#12273](https://github.com/earendil-works/pi/issues/12273))
926
+ - Fixed the `openai-codex` provider ignoring a model's `maxTokens`
927
+ - Fixed fullscreen Kitty images disappearing after a full redraw such as a window resize ([#12010](https://github.com/earendil-works/pi/issues/12010))
928
+ - Fixed text after a multi-row inline image in Markdown drawing over the image ([#12017](https://github.com/earendil-works/pi/issues/12017))
929
+ - Fixed Kitty and iTerm2 images covering overlays drawn over them ([#11584](https://github.com/earendil-works/pi/issues/11584))
930
+ - Fixed Enter on a Tab path menu for an absolute path (`look at /tmp/fi`) or a slash command argument menu (`/open /tm`) submitting the prompt instead of accepting the completion ([#12309](https://github.com/earendil-works/pi/issues/12309), [#12312](https://github.com/earendil-works/pi/pull/12312) by [@acmerfight](https://github.com/acmerfight))
931
+
932
+ ### Removed
933
+
934
+ - Removed the retired `deepseek-v3.2` and `deepseek-v4-flash` from the Qwen Token Plan Team providers; use `deepseek-v4-flash-0731` or `deepseek-v4.1-flash` ([#11773](https://github.com/earendil-works/pi/issues/11773))
935
+
797
936
  ## [1.5.0] - 2026-11-02
798
937
 
799
938
  ### New Features
package/README.md CHANGED
@@ -38,7 +38,7 @@ humain-code
38
38
 
39
39
  The `humain-code` CLI is also available through the `humain-code-cli`, `hc`, `hcc`, `ht`, and `humain` aliases. The old `humain-terminal` command still works but is deprecated. The npm package is `@humain/humain-code` (formerly `@humain/terminal`). The `.humain-terminal` config directory and `HUMAIN_TERMINAL_*` environment variables are unchanged.
40
40
 
41
- To use HUMAIN models, run `/login` and choose **Sign in with HUMAIN**. The order is **HUMAIN Code** (`humain-code-account`), **HUMAIN Node**, **HUMAIN Gateway**, **HUMAIN Fuse**. Code appears only after the selected environment proves native-login readiness; the other providers stay available independently. Use `--env dev|staging|production` (default: dev) for Code only. Then choose a model with `/model`. See [Providers](docs/providers.md#humain-code).
41
+ To use HUMAIN models, run `/login` and choose **Sign in with HUMAIN**. The order is **HUMAIN Code** (`humain-code-account`), **HUMAIN Node**, **HUMAIN Gateway**, **HUMAIN Fuse**. Code appears immediately and shows `checking connection…` while the selected environment is verified; the other providers stay available independently. Production is the default. Use `--env dev` or `--env staging` (`stg` is an alias) to target a non-production Code environment. Then choose a model with `/model`. See [Providers](docs/providers.md#humain-code).
42
42
 
43
43
  Native Code sign-in normally uses encrypted account files with an OS-keychain encryption key. When the keychain is unavailable, you may explicitly choose session-only sign-in before any grant is acquired. Nothing from that sign-in is saved; normal interactive, print, JSON and RPC exits attempt one device-family revocation within 3,000 ms. Unconfirmed revocation is reported on stderr. A crash leaves the session valid until expiry. Persistent accounts are not revoked on normal exit.
44
44
 
@@ -56,7 +56,7 @@ Generating a summary requires separate explicit consent, even if you attach the
56
56
 
57
57
  ## Metadata disclosure
58
58
 
59
- HUMAIN Code CLI automatically sends adoption and performance metadata to the selected built-in `--env` origin: dev `https://code.dev.humain.com` (default), staging `https://code.stg.humain.com`, or production `https://code.humain.com`. Signed-out metadata is pseudonymous, not anonymous: it uses a purpose-specific random install identifier scoped to the environment. Signed-in metadata is account-attributed using the verified HUMAIN Code account. Signed-out history is not retrospectively linked to your account after login; signed-in events do not include the signed-out install identifier.
59
+ HUMAIN Code CLI automatically sends adoption and performance metadata to the selected built-in `--env` origin: production `https://code.humain.com` (default), dev `https://code.dev.humain.com`, or staging `https://code.stg.humain.com`. Signed-out metadata is pseudonymous, not anonymous: it uses a purpose-specific random install identifier scoped to the environment. Signed-in metadata is account-attributed using the verified HUMAIN Code account. Signed-out history is not retrospectively linked to your account after login; signed-in events do not include the signed-out install identifier.
60
60
 
61
61
  Metadata excludes prompts, output, reasoning, paths, tool arguments or results, command text, raw errors, headers, environment dumps, or credentials. CLI analytics metadata is retained for 400 days and diagnostic metadata for 30 days. Fleet-wide metadata is restricted to authorized Forge analytics/admin roles. Authorized account deletion removes identifiable CLI metadata under Forge policy; billing and legal retention are separate. This does not remove local CLI sessions or normal Forge web history, or prevent your selected inference provider from processing conversation content to answer requests.
62
62
 
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{runAgentMonitorCommand}from"./chunks/chunk-R6YQR7TZ.js";import"./chunks/chunk-TGDPZCSW.js";import"./chunks/chunk-HTA325LJ.js";import"./chunks/chunk-XHDVDJM7.js";import"./chunks/chunk-2FYYW6FY.js";import"./chunks/chunk-LB4CIS4F.js";import"./chunks/chunk-VEGJT52D.js";import"./chunks/chunk-6PNQYO6A.js";import"./chunks/chunk-R5OOX7RW.js";import"./chunks/chunk-VFLVWPLZ.js";import"./chunks/chunk-JXWJOIH4.js";process.exitCode=await runAgentMonitorCommand(process.env);
2
+ import{runAgentMonitorCommand}from"./chunks/chunk-7WE77IE3.js";import"./chunks/chunk-4TDNOR36.js";import"./chunks/chunk-2NVGOSBN.js";import"./chunks/chunk-PVNXN2TC.js";import"./chunks/chunk-7OZNMWAJ.js";import"./chunks/chunk-VCMXBP5S.js";import"./chunks/chunk-VEGJT52D.js";import"./chunks/chunk-6HTHDVJC.js";import"./chunks/chunk-B47PNNLL.js";import"./chunks/chunk-VFLVWPLZ.js";import"./chunks/chunk-JXWJOIH4.js";process.exitCode=await runAgentMonitorCommand(process.env);
@@ -0,0 +1,77 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{applyOpenRouterReportedCost,isOpenRouterModel}from"./chunk-J7AP2BUJ.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-JEJQVFWK.js";import{APIError,Anthropic}from"./chunk-4EV7CK26.js";import{iterateSseMessages}from"./chunk-YZMQXAJM.js";import{cacheJsonSerialization,shortHash}from"./chunk-ENBDASDN.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,prefersJsonSchemaStrictSampling,resolveJsonSchemaStrictSampling,
3
+ splitErrorToolResultImages,transformMessages}from"./chunk-CET2MXXN.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{getServerRetryDelayMs,retryProviderRequest}from"./chunk-AI7EHDAX.js";import{appendProviderHttpStatusDiagnostic,normalizeProviderError,safeJsonStringify}from"./chunk-WRYGY5XG.js";import{ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,
4
+ ANTHROPIC_WORKSPACE_ID_ENV}from"./chunk-7H2WNBX7.js";import{registerSessionResourceCleanup}from"./chunk-ZG74NES2.js";import{ToolCallArgumentsStream,parseJsonWithRepair}from"./chunk-LYZ37DJP.js";import"./chunk-AQ4EXORZ.js";import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,resolveTranscript}from"./chunk-Z5UFSRO4.js";import{AssistantMessageEventStream}from"./chunk-GY663MNP.js";import{PROVIDER_CLIENT_VERSIONS,
5
+ SubmissionAdmissionError,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,createRequestObserver,findSubmissionAdmissionError,getIdentityHeaders,getModelHeaders,getSystemMessageText,headersToRecord,mergeHeaders,renderSystemMessageUpdate,reportContentProgress}from"./chunk-ATFZAFMS.js";import"./chunk-JXWJOIH4.js";function supportsDisabledAnthropicThinking(model){let name=`${model.id} ${model.name}`.toLowerCase().replace(/[.\s]+/g,"-");return model.thinkingLevelMap?.off!==null&&!/(?:fable-5|mythos-(?:5|preview)|opus-5-5|sonnet-5-5)(?:-|$)/.test(name)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("HUMAIN_TERMINAL_CACHE_RETENTION",env)==="long"||getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}function getCacheControl(model,cacheRetention,env){let retention=resolveCacheRetention(cacheRetention,env);if(retention==="none")return{retention};let ttl=retention==="long"&&getAnthropicCompat(model).supportsLongCacheRetention?"1h":void 0;return{retention,cacheControl:{type:"ephemera\
6
+ l",...ttl&&{ttl}}}}var claudeCodeVersion=PROVIDER_CLIENT_VERSIONS.claudeCode,claudeCodeTools=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],ccToolLookup=new Map(claudeCodeTools.map(t=>[t.toLowerCase(),t])),toClaudeCodeName=name=>ccToolLookup.get(name.toLowerCase())??name,fromClaudeCodeName=(name,tools)=>{if(tools&&tools.length>0){let lowerName=name.toLowerCase(),
7
+ matchedTool=tools.find(tool=>tool.name.toLowerCase()===lowerName);if(matchedTool)return matchedTool.name}return name};function convertImageBlock(image){return{type:"image",source:{type:"base64",media_type:image.mimeType,data:image.data}}}function convertContentBlocks(content){if(!content.some(c=>c.type==="image"))return sanitizeSurrogates(content.map(c=>c.text).join(`
8
+ `));let blocks=content.map(block=>block.type==="text"?{type:"text",text:sanitizeSurrogates(block.text)}:convertImageBlock(block));return blocks.some(b=>b.type==="text")||blocks.unshift({type:"text",text:"(see attached image)"}),blocks}var FINE_GRAINED_TOOL_STREAMING_BETA="fine-grained-tool-streaming-2025-05-14",INTERLEAVED_THINKING_BETA="interleaved-thinking-2025-05-14",SERVER_SIDE_FALLBACK_BETA="server-side-fallback-2026-07-01",MID_CONVERSATION_OUTPUT_CONFIG_BETA="mid-conversation-output-config\
9
+ -2026-07-01",THINKING_BINDING_CONTROLS_BETA="thinking-binding-controls-2026-08-01",INLINE_TOOLS_BETA="inline-tools-2026-09-15",MESSAGE_THREADS_BETA="message-threads-2026-08-12",DEFERRED_TOOL_PLACEHOLDER={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function shouldUseServerSideFallbackBeta(model){return(model.compat?.allowedFallbackModels?.length??0)>0}function getAnthropicCompat(model){
10
+ let isOpenRouter=model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai");return{supportsEagerToolInputStreaming:model.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:model.compat?.sendSessionAffinityHeaders??isOpenRouter,sessionAffinityFormat:model.compat?.sessionAffinityFormat??(isOpenRouter?"openrouter":void 0),supportsCacheControlOnTools:model.compat?.supportsCacheControlOnTools??!0,allowEmptySignature:model.
11
+ compat?.allowEmptySignature??!1,supportsStrictTools:model.compat?.supportsStrictTools??!1,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsMidConvoToolChanges:model.compat?.supportsMidConvoToolChanges??!1,supportsMessageThreads:model.compat?.supportsMessageThreads??isAnthropicApiHost(model.baseUrl)}}function isAnthropicApiHost(baseUrl){try{return new URL(baseUrl).hostname==="api.anthropic.com"}catch{return!1}}var threadState=new Map,MAX_THREAD_STATE_ENTRIES=1e4,
12
+ NEW_THREAD_ERRORS=new Set(["thread_not_found","thread_already_continued","thread_continue_in_flight","thread_fingerprint_mismatch"]);function setThreadState(sessionId,value){if(threadState.delete(sessionId),threadState.set(sessionId,value),threadState.size>MAX_THREAD_STATE_ENTRIES){let oldest=threadState.keys().next().value;oldest!==void 0&&threadState.delete(oldest)}}registerSessionResourceCleanup(sessionId=>{sessionId?threadState.delete(sessionId):threadState.clear()});function hashThreadPrefix(model,params,messages,credential){
13
+ let{system,tools,thinking,output_config,tool_choice,betas,fallbacks}=params,settings=JSON.stringify([model.provider,model.baseUrl,credential,params.model,system,tools,thinking,output_config,tool_choice,betas,fallbacks]),conversation=JSON.stringify(messages,(key,value)=>{if(key!=="cache_control")return key==="content"&&typeof value=="string"?[{type:"text",text:value}]:value});return shortHash(settings+conversation)}function createThreadRequest(sessionId,credential,params){return{sessionId,credential,
14
+ body:{...params,thread:{type:"create"}}}}function prepareThreadRequest(model,sessionId,credential,params){let state=threadState.get(sessionId);if(state!=="off"){if(state!==void 0&&params.messages.length>state.prefixCount&&hashThreadPrefix(model,params,params.messages.slice(0,state.prefixCount),credential)===state.prefixHash){threadState.delete(sessionId);let{system:_system,tools:_tools,...rest}=params;return{body:{...rest,messages:params.messages.slice(state.prefixCount),thread:{type:"continue",
15
+ previous_message_id:state.replyId}},sessionId,credential}}return createThreadRequest(sessionId,credential,params)}}function getThreadErrorCode(error){let code=error.error?.error?.details?.error_code;return typeof code=="string"?code:void 0}async function sendThreadRequest(thread,params,send,output,signal){try{return{response:await send(thread.body),thread}}catch(error){if(signal?.aborted||!(error instanceof APIError))throw error;let errorCode=getThreadErrorCode(error),startNewThread=errorCode!==
16
+ void 0&&NEW_THREAD_ERRORS.has(errorCode),threadsUnsupported=errorCode==="thread_unsupported_request"||errorCode===void 0&&error.status===400&&error.message.includes("thread");if(!startNewThread&&!threadsUnsupported)throw error;if(appendAssistantMessageDiagnostic(output,{type:"anthropic_thread_fallback",timestamp:Date.now(),error:{message:error.message},details:{reason:errorCode??String(error.status)}}),startNewThread){let created=createThreadRequest(thread.sessionId,thread.credential,params);return{
17
+ response:await send(created.body),thread:created}}let response=await send(params);return setThreadState(thread.sessionId,"off"),{response,thread:void 0}}}function recordThreadReply(model,thread,params,output,isOAuth,allowEmptySignature){if(output.responseId===void 0||output.responseModel!==void 0)return;let reply=convertMessages(transformMessages([output],model,normalizeToolCallId),isOAuth,void 0,allowEmptySignature).messages.filter(message=>message.role==="assistant"),prefix=[...params.messages,
18
+ ...reply];setThreadState(thread.sessionId,{prefixCount:prefix.length,prefixHash:hashThreadPrefix(model,params,prefix,thread.credential),replyId:output.responseId})}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function hasRequestAuth(apiKey,headers){return!!apiKey||hasHeader(headers,"authorization")||hasHeader(headers,"x-api-k\
19
+ ey")||hasHeader(headers,"cf-aig-authorization")}function assertRequestAuth(provider,apiKey,headers){if(!hasRequestAuth(apiKey,headers))throw new Error(`No API key for provider: ${provider}`)}var PiAnthropic=class extends Anthropic{_shouldResolveDefaultCredentials(){return!1}};function getAnthropicFederation(model,apiKey,headers,env){if(model.provider!=="anthropic"||hasRequestAuth(apiKey,headers))return;let federationRuleId=getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV,env),organizationId=getProviderEnvValue(
20
+ ANTHROPIC_ORGANIZATION_ID_ENV,env),identityTokenFile=getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,env);if(!(!federationRuleId||!organizationId||!identityTokenFile))return{organization_id:organizationId,workspace_id:getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV,env),authentication:{type:"oidc_federation",federation_rule_id:federationRuleId,service_account_id:getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,env),identity_token:{source:"file",path:identityTokenFile}}}}var federationClient,
21
+ ANTHROPIC_MESSAGE_EVENTS=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);async function*iterateAnthropicEvents(response,signal){if(!response.body)throw new Error("Attempted to iterate over an Anthropic response with no body");let sawMessageStart=!1,sawMessageEnd=!1;for await(let sse of iterateSseMessages(response.body,{signal})){if(sse.event==="error")throw new Error(sse.data);if(ANTHROPIC_MESSAGE_EVENTS.has(sse.event??""))
22
+ try{let event=parseJsonWithRepair(sse.data);event.type==="message_start"?sawMessageStart=!0:event.type==="message_stop"&&(sawMessageEnd=!0),yield event}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`)}}if(sawMessageStart&&!sawMessageEnd)throw new Error("Anthropic stream ended before message_stop")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,
23
+ compat=getAnthropicCompat(model),normalizedContext=resolveTranscript(context,compat.supportsMidConvoSystemMessages),currentTools=getCurrentTools(normalizedContext.messages);return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{usageIncomplete:!0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},isOAuth=!1;try{let client,usageModel=model,
24
+ inputUsageIncomplete=!0,optionalUsage={},inputTransformations,cacheSessionId=resolveCacheRetention(options?.cacheRetention,options?.env)==="none"?void 0:options?.sessionId,threadSessionId=(options?.client?model.compat?.supportsMessageThreads===!0:compat.supportsMessageThreads)?cacheSessionId:void 0,suppliedClient=options?.client;if(suppliedClient&&options?.beforeSubmission)throw new SubmissionAdmissionError("unsupported-route");if(suppliedClient)client=suppliedClient,isOAuth=!1;else{let apiKey=options?.
25
+ apiKey,federation=getAnthropicFederation(model,apiKey,options?.headers,options?.env);federation||assertRequestAuth(model.provider,apiKey,options?.headers);let copilotDynamicHeaders;if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(normalizedContext.messages);copilotDynamicHeaders=buildCopilotDynamicHeaders({messages:normalizedContext.messages,hasImages})}let created=createClient(model,apiKey,options?.headers,options?.fetch,copilotDynamicHeaders,cacheSessionId,federation,options?.
26
+ identity);client=created.client,isOAuth=created.isOAuthToken}let observe=createRequestObserver(options,{api:"anthropic-messages",provider:model.provider,model:model.id,operation:"chat"}),observeMiddleware=async(request,next,ctx)=>{if(ctx.options!==void 0){if(typeof request.body=="string")await observe(request.body);else if(observe.requiresAdmission)throw new SubmissionAdmissionError("unsupported-route")}return next(request)},requestOptions={...options?.signal?{signal:options.signal}:{},...options?.
27
+ timeoutMs!==void 0?{timeout:options.timeoutMs}:{},...options?.onRequest||options?.beforeSubmission?{middleware:[observeMiddleware]}:{},maxRetries:0};options?.signal?.throwIfAborted();let built=buildParams(model,normalizedContext,isOAuth,options,threadSessionId!==void 0);built.providerThinkingLevel&&(output.providerThinkingLevel=built.providerThinkingLevel);let params=built.params,onPayload=options?.onPayload,nextParams=await onPayload?.call(options,params,model);nextParams!==void 0&&(params={...nextParams,
28
+ stream:!0}),!onPayload&&!suppliedClient&&cacheJsonSerialization(params.messages);let send=body=>retryProviderRequest(async()=>{try{return await client.beta.messages.create(body,requestOptions).asResponse()}catch(error){if(model.provider!=="anthropic"||!isOAuth||!(error instanceof APIError)||error.status!==429||error.headers?.get("anthropic-ratelimit-unified-status")!=="rejected")throw error;let now=Date.now(),resetsAt=Number(error.headers.get("anthropic-ratelimit-unified-reset"))*1e3,validReset=Number.
29
+ isFinite(resetsAt)&&resetsAt>now&&resetsAt<=now+367*864e5;throw appendAssistantMessageDiagnostic(output,createAssistantMessageDiagnostic("provider_http_error",error,{status:429,code:"usage_limit_reached",retryable:!1,...validReset?{resetsAt}:{}})),new Error(error.message,{cause:error})}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal}),prepared=threadSessionId!==void 0&&options?.disableContinuation!==!0?prepareThreadRequest(model,threadSessionId,shortHash(
30
+ options?.apiKey??""),params):void 0,sent=prepared?await sendThreadRequest(prepared,params,send,output,options?.signal):{response:await send(params),thread:void 0},response=sent.response,thread=sent.thread;await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let openBlocks=new Map,openBlock=anthropicIndex=>{let open=openBlocks.get(anthropicIndex);return open===void 0?void 0:{...open,block:output.content[open.
31
+ contentIndex]}};for await(let event of iterateAnthropicEvents(response,options?.signal))if(await options?.onProviderStreamEvent?.(event,model),event.type==="message_start"){output.responseId=event.message.id;let transformations=event.message.input_transformations;Array.isArray(transformations)&&(inputTransformations=transformations);let responseModel=event.message.model;responseModel!==model.id&&(output.responseModel=responseModel);let fallbackCost=responseModel===model.id?void 0:model.compat?.allowedFallbackModels?.
32
+ find(fallback=>fallback.provider===model.provider&&fallback.model===responseModel)?.cost;usageModel=fallbackCost?{...model,id:responseModel,cost:fallbackCost}:model,inputUsageIncomplete=hasIncompleteUsage([event.message.usage?.input_tokens]),optionalUsage.cacheRead=event.message.usage?.cache_read_input_tokens,optionalUsage.cacheWrite=event.message.usage?.cache_creation_input_tokens,optionalUsage.cacheWrite1h=event.message.usage?.cache_creation?.ephemeral_1h_input_tokens,output.usage.input=event.
33
+ message.usage?.input_tokens||0,output.usage.output=event.message.usage?.output_tokens||0,output.usage.cacheRead=event.message.usage?.cache_read_input_tokens||0,output.usage.cacheWrite=event.message.usage?.cache_creation_input_tokens||0,output.usage.cacheWrite1h=event.message.usage?.cache_creation?.ephemeral_1h_input_tokens||0,output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(usageModel,output.usage)}else if(event.type==="\
34
+ content_block_start"){if(event.content_block.type==="fallback"){if(output.content.length>0)throw new Error("Anthropic performed an unsupported mid-output model fallback");continue}event.content_block.type==="text"?(output.content.push({type:"text",text:event.content_block.text??""}),openBlocks.set(event.index,{contentIndex:output.content.length-1}),event.content_block.text?.length&&reportContentProgress(options?.signal),stream2.push({type:"text_start",contentIndex:output.content.length-1,partial:output})):
35
+ event.content_block.type==="thinking"?(output.content.push({type:"thinking",thinking:event.content_block.thinking??"",thinkingSignature:event.content_block.signature??""}),openBlocks.set(event.index,{contentIndex:output.content.length-1}),(event.content_block.thinking?.length||event.content_block.signature)&&reportContentProgress(options?.signal),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})):event.content_block.type==="redacted_thinking"?(output.content.
36
+ push({type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:event.content_block.data,redacted:!0}),openBlocks.set(event.index,{contentIndex:output.content.length-1}),event.content_block.data.length>0&&reportContentProgress(options?.signal),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})):event.content_block.type==="tool_use"&&(output.content.push({type:"toolCall",id:event.content_block.id,name:isOAuth?fromClaudeCodeName(event.content_block.name,
37
+ currentTools):event.content_block.name,arguments:event.content_block.input??{}}),openBlocks.set(event.index,{contentIndex:output.content.length-1,arguments:new ToolCallArgumentsStream}),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output}))}else if(event.type==="content_block_delta"){let open=openBlock(event.index);event.delta.type==="text_delta"?open?.block.type==="text"&&(open.block.text+=event.delta.text,stream2.push({type:"text_delta",contentIndex:open.contentIndex,
38
+ delta:event.delta.text,partial:output})):event.delta.type==="thinking_delta"?open?.block.type==="thinking"&&(open.block.thinking+=event.delta.thinking,stream2.push({type:"thinking_delta",contentIndex:open.contentIndex,delta:event.delta.thinking,partial:output})):event.delta.type==="input_json_delta"?open?.block.type==="toolCall"&&open.arguments!==void 0&&(open.block.arguments=open.arguments.append(event.delta.partial_json),stream2.push({type:"toolcall_delta",contentIndex:open.contentIndex,delta:event.
39
+ delta.partial_json,partial:output})):event.delta.type==="signature_delta"&&open?.block.type==="thinking"&&(open.block.thinkingSignature=open.block.thinkingSignature||"",open.block.thinkingSignature+=event.delta.signature,event.delta.signature.length>0&&reportContentProgress(options?.signal))}else if(event.type==="content_block_stop"){let open=openBlock(event.index);if(openBlocks.delete(event.index),open){let{block,contentIndex:index}=open;block.type==="text"?stream2.push({type:"text_end",contentIndex:index,
40
+ content:block.text,partial:output}):block.type==="thinking"?stream2.push({type:"thinking_end",contentIndex:index,content:block.thinking,partial:output}):block.type==="toolCall"&&open.arguments!==void 0&&(Object.assign(block,open.arguments.finish()),stream2.push({type:"toolcall_end",contentIndex:index,toolCall:block,partial:output}))}}else if(event.type==="message_delta"){let transformations=event.input_transformations;if(Array.isArray(transformations)&&(inputTransformations=transformations),event.
41
+ delta.stop_reason){output.rawStopReason=event.delta.stop_reason;let stopReasonResult=mapStopReason(event.delta.stop_reason,event.delta.stop_details);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}if(event.usage){event.usage.input_tokens!=null&&(output.usage.input=event.usage.input_tokens,inputUsageIncomplete=hasIncompleteUsage([event.usage.input_tokens])),event.usage.output_tokens!=null&&(output.usage.output=event.
42
+ usage.output_tokens),event.usage.cache_read_input_tokens!==void 0&&(optionalUsage.cacheRead=event.usage.cache_read_input_tokens),event.usage.cache_read_input_tokens!=null&&(output.usage.cacheRead=event.usage.cache_read_input_tokens),event.usage.cache_creation_input_tokens!==void 0&&(optionalUsage.cacheWrite=event.usage.cache_creation_input_tokens),event.usage.cache_creation_input_tokens!=null&&(output.usage.cacheWrite=event.usage.cache_creation_input_tokens);let cacheCreation=event.usage.cache_creation;
43
+ cacheCreation?.ephemeral_1h_input_tokens!==void 0&&(optionalUsage.cacheWrite1h=cacheCreation.ephemeral_1h_input_tokens),cacheCreation?.ephemeral_1h_input_tokens!=null&&(output.usage.cacheWrite1h=cacheCreation.ephemeral_1h_input_tokens);let thinkingTokens=event.usage.output_tokens_details?.thinking_tokens;thinkingTokens!==void 0&&(optionalUsage.reasoning=thinkingTokens),event.delta.stop_reason&&(output.usage.usageIncomplete=inputUsageIncomplete||hasIncompleteUsage([event.usage.output_tokens],[event.
44
+ usage.input_tokens,...Object.values(optionalUsage)])),thinkingTokens!=null&&(output.usage.reasoning=thinkingTokens)}output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,output.usage.usageIncomplete||=hasIncompleteUsage([output.usage.totalTokens]),calculateCost(usageModel,output.usage),isOpenRouterModel(model)&&event.usage&&applyOpenRouterReportedCost(output.usage,event.usage)}if(options?.signal?.aborted)throw new Error("Request was aborte\
45
+ d");if(output.stopReason==="pending")throw new Error("Anthropic stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");for(let open of openBlocks.values()){let block=output.content[open.contentIndex];if(block.type==="toolCall"&&open.arguments!==void 0&&output.stopReason!=="length")throw new Error(`Anthropic stream completed with an unfinished tool call: ${block.name} (${block.id})`)}thread&&
46
+ recordThreadReply(model,thread,params,output,isOAuth,compat.allowEmptySignature),inputTransformations&&inputTransformations.length>0&&appendAssistantMessageDiagnostic(output,{type:"anthropic_input_transformations",timestamp:Date.now(),details:{transformations:inputTransformations.map(transformation=>({type:transformation.type??void 0,path:transformation.path??void 0,reason:transformation.reason??void 0}))}}),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){
47
+ output.stopReason=options?.signal?.aborted?"aborted":"error";let refusal=findSubmissionAdmissionError(error);output.errorMessage=refusal?.message??(error instanceof Error?error.message:safeJsonStringify(error)),refusal||appendProviderHttpStatusDiagnostic(output,normalizeProviderError(error)),refusal?appendAssistantMessageDiagnostic(output,{type:"provider_http_error",timestamp:Date.now(),details:{retryable:!1}}):model.provider==="anthropic"&&isOAuth&&error instanceof APIError&&error.status===429&&
48
+ error.type==="rate_limit_error"&&appendAssistantMessageDiagnostic(output,createAssistantMessageDiagnostic("provider_http_error",error,{status:429,retryable:!0}));let retryAfterMs=getServerRetryDelayMs(error);retryAfterMs!==void 0&&(output.retryAfterMs=retryAfterMs),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2};function mapThinkingLevelToEffort(model,level){let mapped=level?model.thinkingLevelMap?.[level]:void 0;if(typeof mapped=="string")return mapped;
49
+ switch(level){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var streamSimple=(model,context,options)=>{getAnthropicFederation(model,options?.apiKey,options?.headers,options?.env)||assertRequestAuth(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinkingEnabled:!1});if(model.
50
+ compat?.forceAdaptiveThinking===!0){let effort=mapThinkingLevelToEffort(model,options.reasoning);return stream(model,context,{...base,thinkingEnabled:!0,effort})}let adjusted=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,options.reasoning,options.thinkingBudgets),maxTokens=clampMaxTokensToContext(model,context,adjusted.maxTokens);return stream(model,context,{...base,maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(adjusted.thinkingBudget,Math.max(0,maxTokens-1024))})};function isOAuthToken(apiKey){
51
+ return apiKey.startsWith("sk-ant-oat")}function createClient(model,apiKey,optionsHeaders,fetch,dynamicHeaders,sessionId,federation,identity){if(model.provider==="github-copilot")return{client:new PiAnthropic({apiKey:null,authToken:apiKey??null,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:mergeHeaders(getIdentityHeaders(model,identity),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},getModelHeaders(model),dynamicHeaders,optionsHeaders)}),isOAuthToken:!1};
52
+ if(apiKey&&isOAuthToken(apiKey))return{client:new PiAnthropic({apiKey:null,authToken:apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:mergeHeaders({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","user-agent":`claude-cli/${claudeCodeVersion}`,"x-app":"cli"},model.headers,optionsHeaders)}),isOAuthToken:!0};let compat=getAnthropicCompat(model),sessionAffinityHeaders={};if(sessionId&&compat.sendSessionAffinityHeaders){let header=compat.sessionAffinityFormat===
53
+ "openrouter"?"x-session-id":"x-session-affinity";sessionAffinityHeaders[header]=sessionId}let defaultHeaders=mergeHeaders(getIdentityHeaders(model,identity),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},sessionAffinityHeaders,model.headers,optionsHeaders);if(federation){let key=JSON.stringify([model.baseUrl,federation]);if(federationClient?.key!==key||federationClient.fetch!==fetch){let client2=new PiAnthropic({apiKey:null,authToken:null,config:federation,baseURL:model.
54
+ baseUrl,dangerouslyAllowBrowser:!0,fetch});federationClient={key,fetch,client:client2}}return{client:federationClient.client.withOptions({defaultHeaders}),isOAuthToken:!1}}return{client:new PiAnthropic({apiKey:apiKey??null,authToken:null,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders}),isOAuthToken:!1}}function getBetaFeatures(model,context,options,{isOAuthToken:isOAuthToken2,nativeToolChanges,messageThreads}){let configuredFeatures;for(let headers of[model.headers,options?.
55
+ headers])for(let[name,value]of Object.entries(headers??{}))name.toLowerCase()==="anthropic-beta"&&(configuredFeatures=value);if(configuredFeatures===null)return[];if(configuredFeatures!==void 0)return[...new Set(configuredFeatures.split(",").map(feature=>feature.trim()).filter(feature=>feature.length>0))];let features=[];return isOAuthToken2&&features.push("claude-code-20250219","oauth-2025-04-20"),shouldUseFineGrainedToolStreamingBeta(model,context)&&features.push(FINE_GRAINED_TOOL_STREAMING_BETA),
56
+ model.reasoning&&options?.thinkingEnabled===!0&&(options.interleavedThinking??!0)&&model.compat?.forceAdaptiveThinking!==!0&&features.push(INTERLEAVED_THINKING_BETA),shouldUseServerSideFallbackBeta(model)&&features.push(SERVER_SIDE_FALLBACK_BETA),model.compat?.supportsMidConvoEffort===!0&&features.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA,THINKING_BINDING_CONTROLS_BETA),nativeToolChanges&&features.push(INLINE_TOOLS_BETA),messageThreads&&features.push(MESSAGE_THREADS_BETA),[...new Set(features)]}function buildParams(model,context,isOAuthToken2,options,messageThreads){
57
+ let{cacheControl}=getCacheControl(model,options?.cacheRetention,options?.env),compat=getAnthropicCompat(model),initialSystemMessage=getInitialSystemMessage(context.messages),initialSystemText=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",transformedMessages=transformMessages(context.messages,model,normalizeToolCallId),conversationMessages=initialSystemMessage?transformedMessages.slice(1):transformedMessages,convertToolDefinitions=(tools,toolCacheControl2)=>convertTools(tools,
58
+ isOAuthToken2,compat.supportsEagerToolInputStreaming,compat.supportsStrictTools,toolCacheControl2),initialTools=initialSystemMessage?.toolsAdded??[],nativeToolChanges=compat.supportsMidConvoSystemMessages&&compat.supportsMidConvoToolChanges&&initialTools.length>0,thinkingDisabled=(model.reasoning||/claude/i.test(model.id))&&options?.thinkingEnabled===!1&&supportsDisabledAnthropicThinking(model),effortMessages=model.compat?.supportsMidConvoEffort===!0&&!thinkingDisabled,converted=convertMessages(
59
+ conversationMessages,isOAuthToken2,cacheControl,compat.allowEmptySignature,effortMessages?model.provider:void 0,nativeToolChanges?convertToolDefinitions:void 0),activeEffort=options?.effort??"high",betaFeatures=getBetaFeatures(model,context,options,{isOAuthToken:isOAuthToken2,nativeToolChanges,messageThreads}),params={model:model.id,messages:effortMessages?insertThinkingLevelMessages(converted,activeEffort):converted.messages,max_tokens:options?.maxTokens??model.maxTokens,stream:!0,...betaFeatures.
60
+ length>0?{betas:betaFeatures}:{}};isOAuthToken2?(params.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...cacheControl?{cache_control:cacheControl}:{}}],initialSystemText&&params.system.push({type:"text",text:sanitizeSurrogates(initialSystemText),...cacheControl?{cache_control:cacheControl}:{}})):initialSystemText&&(params.system=[{type:"text",text:sanitizeSurrogates(initialSystemText),...cacheControl?{cache_control:cacheControl}:{}}]);let toolCacheControl=compat.
61
+ supportsCacheControlOnTools?cacheControl:void 0;if(nativeToolChanges)params.tools=[...convertToolDefinitions(initialTools,toolCacheControl),DEFERRED_TOOL_PLACEHOLDER];else{let tools=getCurrentTools(context.messages);tools.length>0&&(params.tools=convertToolDefinitions(tools,toolCacheControl))}if(thinkingDisabled)params.thinking={type:"disabled"};else if(effortMessages)params.thinking={type:"adaptive",display:options?.thinkingDisplay??"summarized",block_binding:{prefix_mismatch_behavior:"drop_blo\
62
+ ck"}},params.output_config={effort:"low"};else if(model.reasoning&&options?.thinkingEnabled){let display=options.thinkingDisplay??"summarized";model.compat?.forceAdaptiveThinking===!0?(params.thinking={type:"adaptive",display},options.effort&&(params.output_config={effort:options.effort})):params.thinking={type:"enabled",budget_tokens:options.thinkingBudgetTokens||1024,display}}if(options?.metadata){let userId=options.metadata.user_id;typeof userId=="string"&&(params.metadata={user_id:userId})}options?.
63
+ toolChoice&&(typeof options.toolChoice=="string"?params.tool_choice={type:options.toolChoice}:params.tool_choice=options.toolChoice);let allowedFallbackModels=model.compat?.allowedFallbackModels;return allowedFallbackModels&&allowedFallbackModels.length>0&&(params.fallbacks=allowedFallbackModels.map(fallback=>({model:fallback.model}))),{params,providerThinkingLevel:effortMessages?activeEffort:void 0}}function normalizeToolCallId(id){return id.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function convertToolResult(msg,content=msg.
64
+ content){return{type:"tool_result",tool_use_id:msg.toolCallId,content:convertContentBlocks(content),is_error:msg.isError}}function convertMessages(transformedMessages,isOAuthToken2,cacheControl,allowEmptySignature=!1,managedProvider,convertToolDefinitions){let params=[],assistantLevels=new Map,pendingSystemMessages=[],flushPendingSystemMessages=()=>{params.push(...pendingSystemMessages),pendingSystemMessages.length=0};for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(msg.
65
+ role==="system"){let text=renderSystemMessageUpdate(msg),blocks=[];if(text.length>0&&blocks.push({type:"text",text:sanitizeSurrogates(text)}),convertToolDefinitions){let added=msg.toolsAdded??[],redefined=new Set(added.map(tool=>tool.name));for(let tool of msg.toolsRemoved??[])redefined.has(tool.name)||blocks.push({type:"tool_removal",tool:{type:"tool_reference",name:isOAuthToken2?toClaudeCodeName(tool.name):tool.name}});for(let definition of convertToolDefinitions(added))blocks.push({type:"tool\
66
+ _addition",tool:{type:"tool_definition",definition}})}blocks.length>0&&pendingSystemMessages.push({role:"system",content:blocks})}else if(msg.role==="user")if(typeof msg.content=="string")msg.content.trim().length>0&&params.push({role:"user",content:sanitizeSurrogates(msg.content)});else{let filteredBlocks=msg.content.map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:convertImageBlock(item)).filter(b=>b.type==="text"?b.text.trim().length>0:!0);if(filteredBlocks.length===
67
+ 0)continue;params.push({role:"user",content:filteredBlocks})}else if(msg.role==="assistant"){let blocks=[];for(let block of msg.content)if(block.type==="text"){if(block.text.trim().length===0)continue;blocks.push({type:"text",text:sanitizeSurrogates(block.text)})}else if(block.type==="thinking"){if(block.redacted){blocks.push({type:"redacted_thinking",data:block.thinkingSignature});continue}let thinkingSignature=block.thinkingSignature,hasThinkingSignature=!!thinkingSignature&&thinkingSignature.
68
+ trim().length>0;if(block.thinking.trim().length===0&&!hasThinkingSignature)continue;hasThinkingSignature?blocks.push({type:"thinking",thinking:sanitizeSurrogates(block.thinking),signature:thinkingSignature}):blocks.push(allowEmptySignature?{type:"thinking",thinking:sanitizeSurrogates(block.thinking),signature:""}:{type:"text",text:sanitizeSurrogates(block.thinking)})}else block.type==="toolCall"&&blocks.push({type:"tool_use",id:block.id,name:isOAuthToken2?toClaudeCodeName(block.name):block.name,
69
+ input:block.arguments??{}});if(blocks.length===0)continue;flushPendingSystemMessages();let messageIndex=params.length;params.push({role:"assistant",content:blocks}),managedProvider!==void 0&&msg.api==="anthropic-messages"&&msg.provider===managedProvider&&isAnthropicEffort(msg.providerThinkingLevel)&&assistantLevels.set(messageIndex,msg.providerThinkingLevel)}else if(msg.role==="toolResult"){let toolResults=[],errorImages=[],j=i;for(;j<transformedMessages.length&&transformedMessages[j].role==="to\
70
+ olResult";){let toolMsg=transformedMessages[j],split=splitErrorToolResultImages(toolMsg);toolResults.push(convertToolResult(toolMsg,split?.content)),split&&errorImages.push({type:"text",text:split.caption},...split.images.map(convertImageBlock)),j++}i=j-1,params.push({role:"user",content:[...toolResults,...errorImages]})}}if(flushPendingSystemMessages(),cacheControl&&params.length>0){let lastMessage=params[params.length-1];if(lastMessage.role==="user"||lastMessage.role==="system")if(Array.isArray(
71
+ lastMessage.content)){let lastBlock=lastMessage.content[lastMessage.content.length-1];lastBlock&&(lastBlock.type==="text"||lastBlock.type==="image"||lastBlock.type==="tool_result"||lastBlock.type==="tool_addition"||lastBlock.type==="tool_removal")&&(lastBlock.cache_control=cacheControl)}else typeof lastMessage.content=="string"&&(lastMessage.content=[{type:"text",text:lastMessage.content,cache_control:cacheControl}])}return{messages:params,assistantLevels}}function isAnthropicEffort(value){return value===
72
+ "low"||value==="medium"||value==="high"||value==="xhigh"||value==="max"}function insertThinkingLevelMessages(converted,activeEffort){let messages=[];for(let index=0;index<converted.messages.length;index++){let historicalEffort=converted.assistantLevels.get(index);historicalEffort!==void 0&&messages.push({role:"system",content:[],output_config:{effort:historicalEffort}}),messages.push(converted.messages[index])}return messages.push({role:"system",content:[],output_config:{effort:activeEffort}}),messages}
73
+ function shouldUseFineGrainedToolStreamingBeta(model,context){return getCurrentTools(context.messages).length>0&&!getAnthropicCompat(model).supportsEagerToolInputStreaming}var ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties"]),ANTHROPIC_STRICT_STRING_FORMATS=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","u\
74
+ uid"]),isAnthropicStrictUnsupportedKeyword=(key,value)=>ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS.has(key)?!0:key==="minItems"?value!==0&&value!==1:key==="format"?typeof value!="string"||!ANTHROPIC_STRICT_STRING_FORMATS.has(value):!1;function convertTools(tools,isOAuthToken2,supportsEagerToolInputStreaming,supportsStrictTools,cacheControl){return tools?tools.map((tool,index)=>{let strict=prefersJsonSchemaStrictSampling(tool)?void 0:resolveJsonSchemaStrictSampling(tool,supportsStrictTools,isAnthropicStrictUnsupportedKeyword),
75
+ parameters=getJsonSchemaToolParameters(tool,strict),schema=parameters,legacyInputSchema={type:"object",properties:schema.properties??{},required:schema.required??[],...schema.additionalProperties===void 0?{}:{additionalProperties:schema.additionalProperties},...schema.$defs===void 0?{}:{$defs:schema.$defs},...schema.definitions===void 0?{}:{definitions:schema.definitions}},inputSchema=strict===!0?{...parameters,...legacyInputSchema}:legacyInputSchema;return{name:isOAuthToken2?toClaudeCodeName(tool.
76
+ name):tool.name,description:tool.description,...supportsEagerToolInputStreaming?{eager_input_streaming:!0}:{},...strict===!0?{strict:!0}:{},input_schema:inputSchema,...cacheControl&&index===tools.length-1?{cache_control:cacheControl}:{}}}):[]}function mapStopReason(reason,stopDetails){switch(reason){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:stopDetails?.explanation||
77
+ "The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error",errorMessage:"Provider stopped with: sensitive"};default:throw new Error(`Unhandled stop reason: ${reason}`)}}export{stream,streamSimple};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
2
  var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env){return env?.[name]||
3
- (typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}import{timingSafeEqual}from"node:crypto";import{createServer}from"node:http";var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 14" role="img" aria-label="HUMAIN Code"><path fill="#f5f7f7" d="M0 0h6v2H2v10h4v2H0Zm9 0h6v14H9v-2h4V2H9Z"/><path fill="#00b89c" d="M3 4h9v2H3Zm0 4h9v2H3Z"/></svg>';function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(
3
+ (typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}var OAuthRefreshRejectedError=class extends Error{constructor(message="OAuth provider rejected the refresh token"){super(message),this.name="OAuthRefreshRejectedError"}};import{timingSafeEqual}from"node:crypto";import{createServer}from"node:http";var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 14" role="img" aria-label="HUMAIN Code"><path fill="#f5f7f7" d="M0 0h6v2H2v10h4v2H0Zm9 0h6v14H9v-2h4V2H9Z"/><path fill="#00b89c" d="M3 4h9v2H3Zm0 4h9v2H3Z"/></svg>';function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(
4
4
  options.message),details=options.details?escapeHtml(options.details):void 0;return`<!doctype html>
5
5
  <html lang="en">
6
6
  <head>
@@ -75,28 +75,29 @@ options.message),details=options.details?escapeHtml(options.details):void 0;retu
75
75
  </main>
76
76
  </body>
77
77
  </html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}var ALLOWED_ERROR_CODES=new Set(["invalid_request","invalid_client","invalid_grant","unauthorized_client","unsupported_grant_type","invalid_scope","access_denied","unsupported_response_type","server_error","temporarily_unavailable","invalid_token","insufficient_scope","authorization_pending","slow_down","expired_token","invalid_redirect_uri","invalid_client_metadata","invalid_software_statement","unapproved_software_statement","deviceauth_authorization_pending","invalid_request_error","rate_limi\
78
- t_exceeded","usage_limit_reached","previous_response_not_found","websocket_connection_limit_reached"]);function safeOAuthErrorCode(body){let json;try{json=JSON.parse(body)}catch{return}if(typeof json!="object"||json===null)return;let error=json.error,candidate=typeof error=="object"&&error!==null?error.code??error.type:error;return typeof candidate=="string"&&ALLOWED_ERROR_CODES.has(candidate)?candidate:void 0}function stateMatches(received,expected){if(received===null)return!1;let a=Buffer.from(received),b=Buffer.from(expected);return a.length===b.length&&timingSafeEqual(a,b)}function sendPage(response,status,html){response.writeHead(status,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),response.end(html)}async function startOAuthCallbackServer(options){let{providerName,signal}=options;if(signal?.aborted)throw new Error("Login cancelled");let resolveWait=()=>{},rejectWait=()=>{},
79
- waitPromise=new Promise((resolve,reject)=>{resolveWait=resolve,rejectWait=reject});waitPromise.catch(()=>{});let claimed=!1,settled=!1,timer,onAbort=()=>finish({error:new Error("Login cancelled")}),finish=result=>{settled||(settled=!0,timer&&clearTimeout(timer),signal?.removeEventListener("abort",onAbort),"error"in result?rejectWait(result.error):resolveWait(result.value))},server=createServer((request,response)=>{(async()=>{let url=new URL(request.url??"/","http://localhost");if(request.method!==
80
- "GET"||url.pathname!==options.path){sendPage(response,404,oauthErrorHtml("Callback route not found."));return}if(url.searchParams.getAll("state").length>1||url.searchParams.getAll("code").length>1){sendPage(response,400,oauthErrorHtml("Repeated callback parameters."));return}if(options.state!==void 0&&!stateMatches(url.searchParams.get("state"),options.state)){sendPage(response,400,oauthErrorHtml("State mismatch."));return}if(claimed||settled){sendPage(response,409,oauthErrorHtml("This sign-in h\
81
- as already been handled."));return}let error=url.searchParams.get("error");if(error){let safeErrorCode=safeOAuthErrorCode(JSON.stringify({error}));sendPage(response,400,oauthErrorHtml(`${providerName} authorization failed.`,safeErrorCode)),finish({error:new Error(`${providerName} authorization failed${safeErrorCode?`: ${safeErrorCode}`:""}`)});return}let code=url.searchParams.get("code");if(!code){sendPage(response,400,oauthErrorHtml("Missing authorization code."));return}claimed=!0;try{let value=await options.
82
- complete(code);sendPage(response,200,oauthSuccessHtml(`Signed in to ${providerName}. You may now close this page.`)),finish({value})}catch(error2){let failure=error2 instanceof Error?error2:new Error(String(error2));sendPage(response,502,oauthErrorHtml(`${providerName} sign-in failed.`,"Return to the terminal for details.")),finish({error:failure})}})()});await new Promise((resolve,reject)=>{server.once("error",reject),server.listen(options.port,options.host,()=>{server.off("error",reject),resolve()})});
83
- let address=server.address();if(!address||typeof address=="string")throw server.close(),new Error("OAuth callback server did not bind to TCP");server.on("error",error=>finish({error})),signal?.addEventListener("abort",onAbort,{once:!0}),options.timeoutMs!==void 0&&(timer=setTimeout(()=>finish({error:new Error(`${providerName} sign-in timed out`)}),options.timeoutMs));let redirectHost=options.redirectHost??options.host;return{redirectUri:`http://${redirectHost.includes(":")?`[${redirectHost}]`:redirectHost}\
84
- :${address.port}${options.path}`,wait:()=>waitPromise,cancel:()=>{claimed||finish({value:void 0})},close:()=>{finish({error:new Error("OAuth callback server closed")}),server.close()}}}async function waitForCallbackOrManualInput(interaction,callback,prompt){let manualAbort=new AbortController,manualError,manual=interaction.prompt({type:"manual_code",...prompt,signal:manualAbort.signal}).then(input=>(callback?.cancel(),input)).catch(error=>{manualError=error instanceof Error?error:new Error(String(
85
- error)),callback?.cancel()});try{let value=await callback?.wait();if(manualError)throw manualError;if(value!==void 0)return{type:"callback",value};let input=await manual;if(manualError)throw manualError;return{type:"manual",input:input??""}}finally{manualAbort.abort()}}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var decode=s=>atob(s),CLIENT_ID=decode("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),AUTHORIZE_URL="https://claude.ai/oauth/authorize",TOKEN_URL="https://platform.claude.com/v1/oauth/token",CALLBACK_HOST=getProviderEnvValue("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1",CALLBACK_PORT=53692,CALLBACK_PATH="/callback",REDIRECT_URI=`http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`,COPY_CODE_REDIRECT_URI="https://platform.claude.com/oauth/code/callback",ANTHROPIC_BROWSER_LOGIN_METHOD="browser",ANTHROPIC_COPY_CODE_LOGIN_METHOD="\
78
+ t_exceeded","usage_limit_reached","previous_response_not_found","websocket_connection_limit_reached"]);function safeOAuthErrorCode(body){let json;try{json=JSON.parse(body)}catch{return}if(typeof json!="object"||json===null)return;let error=json.error,candidate=typeof error=="object"&&error!==null?error.code??error.type:error;return typeof candidate=="string"&&ALLOWED_ERROR_CODES.has(candidate)?candidate:void 0}function stateMatches(received,expected){if(received===null)return!1;let a=Buffer.from(received),b=Buffer.from(expected);return a.length===b.length&&timingSafeEqual(a,b)}function sendPage(response,status,html){response.writeHead(status,{"content-type":"text/html; charset=utf-8","cache-control":"no-store","referrer-policy":"no-referrer"}),response.end(html)}async function startOAuthCallbackServer(options){let{providerName,signal}=options;if(signal?.aborted)throw new Error("Login cancelled");let resolveWait=()=>{},
79
+ rejectWait=()=>{},waitPromise=new Promise((resolve,reject)=>{resolveWait=resolve,rejectWait=reject});waitPromise.catch(()=>{});let claimed=!1,settled=!1,timer,onAbort=()=>finish({error:new Error("Login cancelled")}),finish=result=>{settled||(settled=!0,timer&&clearTimeout(timer),signal?.removeEventListener("abort",onAbort),"error"in result?rejectWait(result.error):resolveWait(result.value))},server=createServer((request,response)=>{(async()=>{let url=URL.parse(request.url??"/","http://localhost");
80
+ if(request.method!=="GET"||url?.pathname!==options.path){sendPage(response,404,oauthErrorHtml("Callback route not found."));return}if(url.searchParams.getAll("state").length>1||url.searchParams.getAll("code").length>1){sendPage(response,400,oauthErrorHtml("Repeated callback parameters."));return}if(options.state!==void 0&&!stateMatches(url.searchParams.get("state"),options.state)){sendPage(response,400,oauthErrorHtml("State mismatch."));return}if(claimed||settled){sendPage(response,409,oauthErrorHtml(
81
+ "This sign-in has already been handled."));return}if(options.requiredStatus!==void 0){let statuses=url.searchParams.getAll("status");if(statuses.length!==1||statuses[0]!==options.requiredStatus){sendPage(response,400,oauthErrorHtml("Invalid sign-in callback status."));return}}let error=url.searchParams.get("error");if(error){let safeErrorCode=safeOAuthErrorCode(JSON.stringify({error}));sendPage(response,400,oauthErrorHtml(`${providerName} authorization failed.`,safeErrorCode)),finish({error:new Error(
82
+ `${providerName} authorization failed${safeErrorCode?`: ${safeErrorCode}`:""}`)});return}let code=url.searchParams.get("code");if(!code){sendPage(response,400,oauthErrorHtml("Missing authorization code."));return}claimed=!0,timer&&clearTimeout(timer),signal?.removeEventListener("abort",onAbort);try{let value=await options.complete(code);finish({value}),response.destroyed||sendPage(response,200,oauthSuccessHtml(`Signed in to ${providerName}. You may now close this page.`))}catch(error2){let failure=error2 instanceof
83
+ Error?error2:new Error(String(error2));finish({error:failure}),!response.destroyed&&!response.headersSent&&sendPage(response,502,oauthErrorHtml(`${providerName} sign-in failed.`,"Return to the terminal for details."))}})()});await new Promise((resolve,reject)=>{server.once("error",reject),server.listen(options.port,options.host,()=>{server.off("error",reject),resolve()})});let address=server.address();if(!address||typeof address=="string")throw server.close(),new Error("OAuth callback server did\
84
+ not bind to TCP");server.on("error",error=>{claimed||finish({error})}),signal?.addEventListener("abort",onAbort,{once:!0}),signal?.aborted&&onAbort(),!settled&&options.timeoutMs!==void 0&&(timer=setTimeout(()=>{options.continueManuallyOnTimeout?(server.close(),finish({value:void 0})):finish({error:new Error(`${providerName} sign-in timed out`)})},options.timeoutMs));let redirectHost=options.redirectHost??options.host;return{redirectUri:`http://${redirectHost.includes(":")?`[${redirectHost}]`:redirectHost}\
85
+ :${address.port}${options.path}`,wait:()=>waitPromise,cancel:()=>{claimed||finish({value:void 0})},close:()=>{claimed||finish({error:new Error("OAuth callback server closed")}),server.close()}}}async function waitForCallbackOrManualInput(interaction,callback,prompt){let manualAbort=new AbortController,manualError,manual=interaction.prompt({type:"manual_code",...prompt,signal:manualAbort.signal}).then(input=>(callback?.cancel(),input)).catch(error=>{manualError=error instanceof Error?error:new Error(
86
+ String(error)),callback?.cancel()});try{let value=await callback?.wait();if(value!==void 0)return{type:"callback",value};if(manualError)throw manualError;let input=await manual;if(manualError)throw manualError;return{type:"manual",input:input??""}}finally{manualAbort.abort()}}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var decode=s=>atob(s),CLIENT_ID=decode("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),AUTHORIZE_URL="https://claude.ai/oauth/authorize",TOKEN_URL="https://platform.claude.com/v1/oauth/token",CALLBACK_HOST=getProviderEnvValue("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1",CALLBACK_PORT=53692,CALLBACK_PATH="/callback",REDIRECT_URI=`http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`,COPY_CODE_REDIRECT_URI="https://platform.claude.com/oauth/code/callback",ANTHROPIC_BROWSER_LOGIN_METHOD="browser",ANTHROPIC_COPY_CODE_LOGIN_METHOD="\
86
87
  copy_code",SCOPES="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";function parseAuthorizationInput(input){let value=input.trim();if(!value)return{};try{let url=new URL(value);return{code:url.searchParams.get("code")??void 0,state:url.searchParams.get("state")??void 0}}catch{}if(value.includes("#")){let[code,state]=value.split("#",2);return{code,state}}if(value.includes("code=")){let params=new URLSearchParams(value);return{code:params.
87
88
  get("code")??void 0,state:params.get("state")??void 0}}return{code:value}}function formatErrorDetails(error){if(error instanceof Error){let details=[`${error.name}: ${error.message}`],errorWithCode=error;return errorWithCode.code&&details.push(`code=${errorWithCode.code}`),typeof errorWithCode.errno<"u"&&details.push(`errno=${String(errorWithCode.errno)}`),typeof error.cause<"u"&&details.push(`cause=${formatErrorDetails(error.cause)}`),error.stack&&details.push(`stack=${error.stack}`),details.join(
88
- "; ")}return String(error)}async function postJson(url,body,signal){let response=await fetch(url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(body),signal:AbortSignal.any([signal,AbortSignal.timeout(3e4)])}),responseBody=await response.text();if(!response.ok){let code=safeOAuthErrorCode(responseBody);throw new Error(`HTTP request failed. status=${response.status}; url=${url}${code?`; error=${code}`:""}`)}return responseBody}function parseTokenResponse(responseBody,requestName){
89
- let data;try{data=JSON.parse(responseBody)}catch{throw new Error(`${requestName} returned invalid JSON`)}let token=data;if(typeof token!="object"||token===null||typeof token.access_token!="string"||!token.access_token.trim()||typeof token.refresh_token!="string"||!token.refresh_token.trim()||typeof token.expires_in!="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0)throw new Error(`${requestName} returned an invalid token response`);let credential={type:"oauth",refresh:token.refresh_token,
90
- access:token.access_token,expires:Date.now()+token.expires_in*1e3-300*1e3};return applyIdentity(credential,token,"email_address"),credential}function applyIdentity(credential,data,emailField){let safeIdentity=value=>typeof value=="string"&&value.trim().length>0&&value.length<=320&&!/[\p{Cc}\p{Cf}]/u.test(value)&&![credential.access,credential.refresh].some(secret=>value.includes(secret)),safeUuid=value=>safeIdentity(value)&&/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value);if(typeof data.
91
- account=="object"&&data.account!==null&&!Array.isArray(data.account)){let account=data.account;safeUuid(account.uuid)&&(credential.accountId=account.uuid);let email=account[emailField];safeIdentity(email)&&email.includes("@")&&(credential.accountLabel=email)}if(typeof data.organization=="object"&&data.organization!==null&&!Array.isArray(data.organization)){let organization=data.organization;if(safeUuid(organization.uuid)&&(credential.organizationId=organization.uuid,safeIdentity(organization.name)&&
92
- typeof credential.accountLabel=="string")){let label=`${credential.accountLabel} \xB7 ${organization.name}`;safeIdentity(label)&&(credential.accountLabel=label)}}}async function recoverProfileIdentity(credential,signal){if(credential.organizationId!==void 0)return credential;try{let response=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${credential.access}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.any([signal,AbortSignal.timeout(
93
- 1e4)])});if(response.ok){let profile=await response.json();typeof profile=="object"&&profile!==null&&!Array.isArray(profile)&&applyIdentity(credential,profile,"email")}}catch{}return signal.throwIfAborted(),credential}async function exchangeAuthorizationCode(code,state,verifier,redirectUri,signal){let responseBody;try{responseBody=await postJson(TOKEN_URL,{grant_type:"authorization_code",client_id:CLIENT_ID,code,state,redirect_uri:redirectUri,code_verifier:verifier},signal)}catch(error){throw new Error(
94
- `Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`)}return recoverProfileIdentity(parseTokenResponse(responseBody,"Token exchange"),signal)}async function loginAnthropic(interaction){let{verifier,challenge}=await generatePKCE(),startCallbackServer=port=>startOAuthCallbackServer({providerName:"Anthropic",host:CALLBACK_HOST,port,path:CALLBACK_PATH,redirectHost:"localhost",state:verifier,complete:async code=>code,
95
- signal:interaction.signal}),callback=await startCallbackServer(CALLBACK_PORT).catch(()=>startCallbackServer(0)).catch(()=>{}),redirectUri=callback?.redirectUri??REDIRECT_URI;try{let authParams=new URLSearchParams({code:"true",client_id:CLIENT_ID,response_type:"code",redirect_uri:redirectUri,scope:SCOPES,code_challenge:challenge,code_challenge_method:"S256",state:verifier});interaction.notify({type:"auth_url",url:`${AUTHORIZE_URL}?${authParams.toString()}`,instructions:"Complete login in your bro\
96
- wser. If the browser is on another machine, paste the final redirect URL here."});let result=await waitForCallbackOrManualInput(interaction,callback,{message:"Complete login in your browser, or paste the authorization code / redirect URL here:",placeholder:redirectUri}),code,state=verifier;if(result.type==="callback")code=result.value;else{let parsed=parseAuthorizationInput(result.input);if(parsed.state&&parsed.state!==verifier)throw new Error("OAuth state mismatch");code=parsed.code,state=parsed.
97
- state??verifier}if(!code)throw new Error("Missing authorization code");return interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."}),await exchangeAuthorizationCode(code,state,verifier,redirectUri,interaction.signal)}finally{callback?.close()}}async function loginAnthropicCopyCode(interaction){let{verifier,challenge}=await generatePKCE(),authParams=new URLSearchParams({code:"true",client_id:CLIENT_ID,response_type:"code",redirect_uri:COPY_CODE_REDIRECT_URI,scope:SCOPES,
98
- code_challenge:challenge,code_challenge_method:"S256",state:verifier});interaction.notify({type:"auth_url",url:`${AUTHORIZE_URL}?${authParams.toString()}`,instructions:"Complete login in your browser, then copy the code Anthropic shows and paste it here."});let input=await interaction.prompt({type:"manual_code",message:"Paste the code Anthropic shows after you sign in:",placeholder:"code#state",signal:interaction.signal}),parsed=parseAuthorizationInput(input);if(parsed.state&&parsed.state!==verifier)
99
- throw new Error("OAuth state mismatch");if(!parsed.code)throw new Error("Missing authorization code");return interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."}),await exchangeAuthorizationCode(parsed.code,parsed.state??verifier,verifier,COPY_CODE_REDIRECT_URI,interaction.signal)}async function refreshAnthropicToken(refreshToken,signal){let responseBody;try{responseBody=await postJson(TOKEN_URL,{grant_type:"refresh_token",client_id:CLIENT_ID,refresh_token:refreshToken},
100
- signal)}catch(error){throw new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`)}return parseTokenResponse(responseBody,"Anthropic token refresh")}var anthropicOAuth={name:"Anthropic (Claude Pro/Max)",isSubscription:!0,async login(interaction){let method=await interaction.prompt({type:"select",message:"Select Anthropic login method:",options:[{id:ANTHROPIC_BROWSER_LOGIN_METHOD,label:"Browser login (default)"},{id:ANTHROPIC_COPY_CODE_LOGIN_METHOD,
101
- label:"Copy code login (headless)"}]});if(method===ANTHROPIC_COPY_CODE_LOGIN_METHOD)return loginAnthropicCopyCode(interaction);if(method!==ANTHROPIC_BROWSER_LOGIN_METHOD)throw new Error(`Unknown Anthropic login method: ${method}`);return loginAnthropic(interaction)},async refresh(credential,signal){let refreshed=await refreshAnthropicToken(credential.refresh,signal);return{...credential,...refreshed,...credential.organizationId!==void 0&&refreshed.organizationId===void 0?{accountLabel:credential.
102
- accountLabel??refreshed.accountLabel}:{}}},async toAuth(credential){return{apiKey:credential.access}}};export{anthropicOAuth};
89
+ "; ")}return String(error)}var OAuthHttpError=class extends Error{};async function postJson(url,body,signal){let response=await fetch(url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(body),signal:AbortSignal.any([signal,AbortSignal.timeout(3e4)])}),responseBody=await response.text();if(!response.ok){let code=safeOAuthErrorCode(responseBody);throw body.grant_type==="refresh_token"&&response.status===400&&code==="invalid_grant"?new OAuthRefreshRejectedError(
90
+ "OAuth provider rejected the refresh token; status=400; error=invalid_grant"):new OAuthHttpError(`HTTP request failed. status=${response.status}; url=${url}${code?`; error=${code}`:""}`)}return responseBody}function parseTokenResponse(responseBody,requestName){let data;try{data=JSON.parse(responseBody)}catch{throw new Error(`${requestName} returned invalid JSON`)}let token=data;if(typeof token!="object"||token===null||typeof token.access_token!="string"||!token.access_token.trim()||typeof token.
91
+ refresh_token!="string"||!token.refresh_token.trim()||typeof token.expires_in!="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0)throw new Error(`${requestName} returned an invalid token response`);let credential={type:"oauth",refresh:token.refresh_token,access:token.access_token,expires:Date.now()+token.expires_in*1e3-300*1e3};return applyIdentity(credential,token,"email_address"),credential}function applyIdentity(credential,data,emailField){let safeIdentity=value=>typeof value==
92
+ "string"&&value.trim().length>0&&value.length<=320&&!/[\p{Cc}\p{Cf}]/u.test(value)&&![credential.access,credential.refresh].some(secret=>value.includes(secret)),safeUuid=value=>safeIdentity(value)&&/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value);if(typeof data.account=="object"&&data.account!==null&&!Array.isArray(data.account)){let account=data.account;safeUuid(account.uuid)&&(credential.accountId=account.uuid);let email=account[emailField];safeIdentity(email)&&email.includes("@")&&
93
+ (credential.accountLabel=email)}if(typeof data.organization=="object"&&data.organization!==null&&!Array.isArray(data.organization)){let organization=data.organization;if(safeUuid(organization.uuid)&&(credential.organizationId=organization.uuid,safeIdentity(organization.name)&&typeof credential.accountLabel=="string")){let label=`${credential.accountLabel} \xB7 ${organization.name}`;safeIdentity(label)&&(credential.accountLabel=label)}}}async function recoverProfileIdentity(credential,signal){if(credential.
94
+ organizationId!==void 0)return credential;try{let response=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${credential.access}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.any([signal,AbortSignal.timeout(1e4)])});if(response.ok){let profile=await response.json();typeof profile=="object"&&profile!==null&&!Array.isArray(profile)&&applyIdentity(credential,profile,"email")}}catch{}return signal.throwIfAborted(),credential}async function exchangeAuthorizationCode(code,state,verifier,redirectUri,signal){
95
+ let responseBody;try{responseBody=await postJson(TOKEN_URL,{grant_type:"authorization_code",client_id:CLIENT_ID,code,state,redirect_uri:redirectUri,code_verifier:verifier},signal)}catch(error){throw new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`)}return recoverProfileIdentity(parseTokenResponse(responseBody,"Token exchange"),signal)}async function loginAnthropic(interaction){let{verifier,
96
+ challenge}=await generatePKCE(),startCallbackServer=port=>startOAuthCallbackServer({providerName:"Anthropic",host:CALLBACK_HOST,port,path:CALLBACK_PATH,redirectHost:"localhost",state:verifier,complete:async code=>code,signal:interaction.signal}),callback=await startCallbackServer(CALLBACK_PORT).catch(()=>startCallbackServer(0)).catch(()=>{}),redirectUri=callback?.redirectUri??REDIRECT_URI;try{let authParams=new URLSearchParams({code:"true",client_id:CLIENT_ID,response_type:"code",redirect_uri:redirectUri,
97
+ scope:SCOPES,code_challenge:challenge,code_challenge_method:"S256",state:verifier});interaction.notify({type:"auth_url",url:`${AUTHORIZE_URL}?${authParams.toString()}`,instructions:"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here."});let result=await waitForCallbackOrManualInput(interaction,callback,{message:"Complete login in your browser, or paste the authorization code / redirect URL here:",placeholder:redirectUri}),code,state=verifier;if(result.
98
+ type==="callback")code=result.value;else{let parsed=parseAuthorizationInput(result.input);if(parsed.state&&parsed.state!==verifier)throw new Error("OAuth state mismatch");code=parsed.code,state=parsed.state??verifier}if(!code)throw new Error("Missing authorization code");return interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."}),await exchangeAuthorizationCode(code,state,verifier,redirectUri,interaction.signal)}finally{callback?.close()}}async function loginAnthropicCopyCode(interaction){
99
+ let{verifier,challenge}=await generatePKCE(),authParams=new URLSearchParams({code:"true",client_id:CLIENT_ID,response_type:"code",redirect_uri:COPY_CODE_REDIRECT_URI,scope:SCOPES,code_challenge:challenge,code_challenge_method:"S256",state:verifier});interaction.notify({type:"auth_url",url:`${AUTHORIZE_URL}?${authParams.toString()}`,instructions:"Complete login in your browser, then copy the code Anthropic shows and paste it here."});let input=await interaction.prompt({type:"manual_code",message:"\
100
+ Paste the code Anthropic shows after you sign in:",placeholder:"code#state",signal:interaction.signal}),parsed=parseAuthorizationInput(input);if(parsed.state&&parsed.state!==verifier)throw new Error("OAuth state mismatch");if(!parsed.code)throw new Error("Missing authorization code");return interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."}),await exchangeAuthorizationCode(parsed.code,parsed.state??verifier,verifier,COPY_CODE_REDIRECT_URI,interaction.signal)}
101
+ async function refreshAnthropicToken(refreshToken,signal){let responseBody;try{responseBody=await postJson(TOKEN_URL,{grant_type:"refresh_token",client_id:CLIENT_ID,refresh_token:refreshToken},signal)}catch(error){throw error instanceof OAuthRefreshRejectedError||error instanceof OAuthHttpError?error:new Error("Anthropic token refresh request failed")}return parseTokenResponse(responseBody,"Anthropic token refresh")}var anthropicOAuth={name:"Anthropic (Claude Pro/Max)",isSubscription:!0,async login(interaction){
102
+ let method=await interaction.prompt({type:"select",message:"Select Anthropic login method:",options:[{id:ANTHROPIC_BROWSER_LOGIN_METHOD,label:"Browser login (default)"},{id:ANTHROPIC_COPY_CODE_LOGIN_METHOD,label:"Copy code login (headless)"}]});if(method===ANTHROPIC_COPY_CODE_LOGIN_METHOD)return loginAnthropicCopyCode(interaction);if(method!==ANTHROPIC_BROWSER_LOGIN_METHOD)throw new Error(`Unknown Anthropic login method: ${method}`);return loginAnthropic(interaction)},async refresh(credential,signal){
103
+ let refreshed=await refreshAnthropicToken(credential.refresh,signal);return{...credential,...refreshed,...credential.organizationId!==void 0&&refreshed.organizationId===void 0?{accountLabel:credential.accountLabel??refreshed.accountLabel}:{}}},async toAuth(credential){return{apiKey:credential.access}}};export{anthropicOAuth};
@@ -0,0 +1,15 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-WGXMYMPE.js";import{iterateOpenAIStream}from"./chunk-QJB5YI3I.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-46C6D7UC.js";import"./chunk-YZMQXAJM.js";import{cacheJsonSerialization}from"./chunk-ENBDASDN.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-CET2MXXN.js";
3
+ import"./chunk-YTVFIA3A.js";import"./chunk-L2ZPNLYD.js";import{getServerRetryDelayMs,retryProviderRequest}from"./chunk-AI7EHDAX.js";import{appendProviderHttpStatusDiagnostic,formatProviderError,normalizeProviderError}from"./chunk-WRYGY5XG.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-CIA6V3BP.js";import"./chunk-LYZ37DJP.js";import"./chunk-AQ4EXORZ.js";import"./chunk-FACBDLFU.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,
4
+ resolveTranscriptTools}from"./chunk-Z5UFSRO4.js";import{AssistantMessageEventStream}from"./chunk-GY663MNP.js";import{createRequestObserver,getIdentityHeaders,headersToRecord,observeFetch}from"./chunk-ATFZAFMS.js";import"./chunk-JXWJOIH4.js";var AZURE_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode","azure"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let deploymentName=resolveDeploymentName(model,options),output={role:"assistant",content:[],api:"azure-openai-responses",provider:model.provider,model:model.id,usage:{usageIncomplete:!0,input:0,
5
+ output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let observe=createRequestObserver(options,{api:model.api,provider:model.provider,model:model.id,operation:"chat"}),client=createClient(model,apiKey,options,observeFetch(options?.fetch,observe)),grammarToolInputProperties=createGrammarToolInputProperties(
6
+ getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),params=buildParams(model,normalizedContext,options,deploymentName,grammarToolInputProperties),onPayload=options?.onPayload,nextParams=await onPayload?.call(options,params,model);nextParams!==void 0&&(params=nextParams),onPayload||cacheJsonSerialization(params.input);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},
7
+ {data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(iterateOpenAIStream(openaiStream,response,client),output,stream2,model,{signal:options?.signal,onProviderStreamEvent:options?.
8
+ onProviderStreamEvent,grammarToolInputProperties}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Azure OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){output.stopReason=options?.signal?.aborted?"aborted":
9
+ "error";let normalizedError=normalizeProviderError(error);output.errorMessage=formatProviderError(normalizedError,"Azure OpenAI API error"),appendProviderHttpStatusDiagnostic(output,normalizedError);let retryAfterMs=getServerRetryDelayMs(error);retryAfterMs!==void 0&&(output.retryAfterMs=retryAfterMs),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API k\
10
+ ey for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function createClient(model,apiKey,options,fetch){let headers={...getIdentityHeaders(model,options?.identity),...model.headers};options?.headers&&Object.assign(headers,options.headers);
11
+ let{baseUrl,apiVersion}=resolveAzureConfig(model,options);return new AzureOpenAI({apiKey,apiVersion,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers,baseURL:baseUrl})}function buildParams(model,context,options,deploymentName,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,
12
+ transcriptTools=resolveTranscriptTools(context.messages,getResponsesToolSupport({supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch})),messages=convertResponsesMessages(model,context,AZURE_TOOL_CALL_PROVIDERS,{grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{supportsStrictMode:model.compat?.supportsStrictMode??!0,
13
+ supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1}}),params={model:deploymentName,input:messages,stream:!0,prompt_cache_key:options?.cacheRetention==="none"||model.compat?.promptCacheKeyMode==="disabled"?void 0:clampOpenAIPromptCacheKey(options?.sessionId),store:!1};options?.maxTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),transcriptTools.requestTools.
14
+ length>0&&(params.tools=convertResponsesTools(transcriptTools.requestTools,{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice);let reasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0);if(model.reasoning)if(reasoningEffort){let effort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.
15
+ reasoningEffort:reasoningEffort;params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});let samplingParams=resolveSamplingParams(model,reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}export{stream,streamSimple};